2

I have defined a state with array and objects inside as follow.

constructor(props) {
    super(props);
     this.state = {
        posts: [
            {
                id: '',
                assignee_name: '',
                assignee_link: ''
            }
        ]
    }
}

From the API, it is returning me some data in res which I am not sure how to assign it to the state initiated.

axios.get('http://localhost:3000/api/posts')
            .then(res  => {
                this.setState({
                    posts: res.data
                });
            })

I tried following lines

posts.assignee_link: res.data.assignee_link 

But this one gives me error.

Can anybody teach me how can I assign it ?

user1687891
  • 794
  • 2
  • 14
  • 30
  • 1
    `posts` is an array but you're trying to access as object. Refer this post -> https://stackoverflow.com/a/38742438/2845389 – Kaushik Aug 27 '19 at 04:19
  • posts is an array, so you should give it index value when setting state like this `posts[0].assignee_link: res.data.assignee_link` – Robin Aug 27 '19 at 04:33

2 Answers2

2

If I understand correctly, you want to update the assignee_link of the first post in the posts array state of your component, with data returned from your axios request.

One way to achieve that would be as detailed below:

axios.get('http://localhost:3000/api/posts').then(res  => {

    this.setState(prevState => {

        /* Get first post from state */
        const oldPost = prevState.posts[0];

        /* Spread old post into new post object (clone), and apply
           updated assignee_link to new cloned post */
        const newPost = { 
            ...oldPost, 
            assignee_link : res.data.assignee_link 
        };

        /* Return new array with single newPost item. This array will 
           replace the state of the component */
        return [newPost];
    });
});
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
2

This will work please try

axios.get('http://localhost:3000/api/posts')
.then(res  => {
    const values = {
        id: res.data.id,
        assignee_name: res.data.assignee_name,
        assignee_link: res.data.assignee_link
    };
    this.setState({
        posts: values
    });
})