0

I basically want to put each string in the array in a separated div, I'm trying to do this but is not rendering anything

export default class Loja extends Component {
      state = {
        loja: {},
        lojaInfo: {},
        category: []
      }

      async componentDidMount() {
        const { id } = this.props.match.params;

        const response = await api.get(`/stores/${id}`);

        const { category, ...lojaInfo } = response.data

        this.setState({ loja: category, lojaInfo });

        console.log(category)

      }

      render() {
        const { category } = this.state;


        return (

            <p>{category.map(cat => <div>{cat}</div>)}</p>

        );
      }
    }

The console.log(category) shows this:

enter image description here

3
  • You're not updating the category part of the state in this line this.setState({ loja: category, lojaInfo }); Commented Dec 10, 2019 at 1:34
  • Sorry im kinda new on react can you show in code? Commented Dec 10, 2019 at 1:36
  • The field category in state is always an empty array. Commented Dec 10, 2019 at 2:27

2 Answers 2

1

The error is that you're updating 2 properties inside the componentDidMount, one is loja: category and the second property is lojaInfo, but in the render() method you're accessing this.state.category which still is an empty string.

What you want to do instead is, inside of your componentDidMount update your state like this:

this.setState({
  category,
  lojaInfo,
});
Sign up to request clarification or add additional context in comments.

Comments

1

you've added your category into the loja object in the state.

something like this should work:

async componentDidMount() {
    const { id } = this.props.match.params;
    const response = await api.get(`/stores/${id}`);
    const { category, ...lojaInfo } = response.data
    this.setState({ category, lojaInfo });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.