user1687891
user1687891

Reputation: 864

How to assign API return value to state?

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 ?

Upvotes: 2

Views: 351

Answers (2)

Sanchit Srivastava
Sanchit Srivastava

Reputation: 66

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
    });
})

Upvotes: 2

Dacre Denny
Dacre Denny

Reputation: 30360

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];
    });
});

Upvotes: 2

Related Questions