0

I'm trying to update api with React Redux using createAsyncThunk, Status Code is 200, but data is not updated.

Api are developed with Laravel Passport and working fine using Postman.

    export const fetchUpdateLead = createAsyncThunk(
        'leads/fetchUpdateLead',
        async (event) => {
            const data = new FormData(event.target);
            return await fetch("https://api.test/api/edit/173599", {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    nome_cliente: data.get('name'),
                    telefono_cliente: data.get('phone')
                }),
            }).then(
                (res) => res.json()
            );
    });


const leadsSlice = createSlice({
    name: "leads",
    initialState: {
        leads: [],
        status: null
    },
    reducers: {},
    extraReducers: {
        [fetchUpdateLead.fulfilled]: (state, action) => {
            state.status = "updated";
        },
    }
});

export default leadsSlice.reducer;
cloude
  • 338
  • 5
  • 18

1 Answers1

0

Well, the code you are writing is only updating state.status, not state.data or anything else. If you want that to happen, you have to write it - it will not happen by itself.

Generally, please be aware that the object notation of extraReducers here is not the recommended way of using it, you should be using the builder callback notation. You are probably following outdated documentation.

I would highly recommend you read the chapter on using createAsyncThunk of the official Redux tutorial: https://redux.js.org/tutorials/essentials/part-5-async-logic

Chapters 7 and 8 might also be of interest to you as they go into using RTK Query, which automates most of that.

phry
  • 35,762
  • 5
  • 67
  • 81
  • @fri Thank you. I'm started to learn React from little time, I come from jquery, but I see a lot of confusion. This is that I understand until now: React Classes deprecated, then another course say to use React Hook, then another course say not use React Hook but React with Redux, then another course say not use only React Redux but use React with Redux Toolkit, a lot of confusion for me. – cloude Apr 17 '22 at 09:36
  • Okay, this is the current state: modern React uses Hooks, not classes. Modern Redux uses Toolkit. Keep state local first and only move it into Redux if it is global. Apart from that: usually, check the official documentation first. Unfortunately, for React it is a bit outdated, but they are reworking them and you can check the beta of the new docs at https://beta.reactjs.org/ . For Redux, stay with the "essentials" tutorial I linked above. – phry Apr 17 '22 at 20:25