Bodman
Bodman

Reputation: 91

Update State with record returned from API, after being updated

I'm currently trying to learn react and I'm struggling with the correct way to update a record within the state after its changes have been saved and returned via an API, so far the only way I can get it to work is by returning the entire list of records and updating the state with the new list through the reducer. Which is not ideal as I don't want to have to reload multiple records for one record's changes.

The Reducer code below currently adds the updated record onto the end of the state's data rather than replacing the existing record.

        case 'EDIT_AUTHOR': 
            return {
                ...state,
                authors: [...state.authors, action.payload]
            }

This is the States Update Function

    // Edit Author
    async function editAuthor(author) {
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        }

        try 
        {
            const res = await axios.put('api/v1/authors', author, config);

            dispatch({
                type: 'EDIT_AUTHOR',
                payload: res.data.data
            });
        } 
        catch (err) 
        {
            dispatch({
                type: 'AUTHORS_ERROR',
                payload: err.response.data.error
            });
        }
    }

Thanks in advance for any advice and please do let me know if you would like to see any more of the code, I think I have provided everything that is needed.

Upvotes: 1

Views: 142

Answers (1)

Flui
Flui

Reputation: 146

when the ather has an id you can identify the user by that. As map returns a new array there is no need for spreading the old author list.

case 'EDIT_AUTHOR': {
    const updatedAuthor = action.payload;
    const authors = state.authors.map(author => updatedAuthor.id === author.id ? updatedAuthor : author);

            return {
                ...state,
                authors,
            }
}

Upvotes: 1

Related Questions