DevGe
DevGe

Reputation: 1449

How to push the data from api to my initial state list items using the redux toolkit?

I'm currently new on react redux toolkit and now I am practicing on this management. Right now I want to do is to push all datas from my api to my initial state list_remarks reducers.

Question: How or where to put my api to push all the datas from api to my initial state list?

Ex API: localhost:8000/api/list_remarks

Here is my CreateSlice:

import { createSlice } from '@reduxjs/toolkit';

export const RemarksSlice = createSlice({
    name:"check_in_remarks",
    initialState: {
        list_remarks:[],
        check_in_remarks: null,
    },
    reducers: {
        list_remarks: (state, action) => {
            state.remarks = action.payload
        },
        add_check_in_remarks: (state, action) => {
            state.check_in_remarks = action.payload
        }
    }
})

export const { add_check_in_remarks, list_remarks } = RemarksSlice.actions;

export const AddRemarks = (state) => state.check_in_remarks.check_in_remarks;
export const ListRemarks = (state) => state.list_remarks.list_remarks;

export default RemarksSlice.reducer;

Upvotes: 1

Views: 7188

Answers (2)

Deep1man3
Deep1man3

Reputation: 192

add action setRemarks and setError:

reducers: {
...
   // Getting a list of remarks in a store
   setRemarks: (state, action) => {
      state.remarks = action.payload
   }
   // In case of problems with receiving, we will add an error to the store.
   setError: (state, action) => {
      state.error = action.payload
   }
... 
}

and add asyncThunk (about createAsyncThunk function):

   export const fetchRemaks = createAsyncThunk(
   'remarks/fetch',
   async (_, {dispatch}) => {
    // here is your receiving remarks function
    fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json())
        .then(remarks => dispatch(setRemarks(remarks)))
        .catch(error => dispatch(setError(error)))
   }
)

How to use:

export default function App() {
  
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const { error } = useSelector(state => state.remarks)
  useEffect(() => {
    setLoading(true)
    dispatch(fetchRemaks())
    setLoading(false)
  })

  return (
    <div className="App">
     {error && <b>{error}</b>}
     {loading 
        ? 'loading...'
        : 'remarks'
     }
    </div>
  );
}

Upvotes: 0

John Lobo
John Lobo

Reputation: 15319

You can use createAsyncThunk Ref:https://redux-toolkit.js.org/api/createAsyncThunk

I can provide you basic snippet which might help you

export const getPosts = createAsyncThunk(
    'posts/getPosts',

    async (arg, { dispatch, getState, extra, requestId, signal, rejectWithValue }) => {
      
        return fetch(
            `https://jsonplaceholder.typicode.com/posts?_limit=${arg.limit}`
        ).then((res) => {
            if (!res.ok) {
                
                return rejectWithValue([], "api url not found from");
            }
            return res.json()
        }).catch(error => {
           
            return rejectWithValue([], error);
           
        })
    }

)

In createSlice

    export const RemarksSlice = createSlice({
    name:"check_in_remarks",
    initialState: {
        list_remarks:[],
        check_in_remarks: null,
status :null
    },
    reducers: {
        list_remarks: (state, action) => {
            state.remarks = action.payload
        },
        add_check_in_remarks: (state, action) => {
            state.check_in_remarks = action.payload
        }
    },
     extraReducers: {

        [getPosts.pending]: (state, action) => {
          
            state.status = 'loading'
        },
        [getPosts.fulfilled]: (state, { payload, meta }) => {

          
            state.list_remarks = payload
            state.status = 'success'
        },
        [getPosts.rejected]: (state, action) => {
            state.status = 'failed'
        },
    }
})

To dispatch from any useEffect or anywhere you wanted then

 React.useEffect(() => {
        dispatch(getPosts({ limit: 5 }));
       
    }, [])

Upvotes: 2

Related Questions