score:9
it is happening because your reducer function is not a pure function, it should not be having any asynchronous calls.
something like this should work. it will fix the error you are getting
const products = createslice({
name: "products",
initialstate: {
products: []
},
reducers: {
reducer2: (state, { payload }) => {
return { products: [...state.products, ...payload]}
})
}
}
});
and api should be called outside
const fetchproducts = () => {
axios.get('myurl')
.then(response => {
//console.log(response.data.products);
store.dispatch(products.actions.reducer2(response.data.products))
})
};
ps: haven't tried running above code, you may have to make modifications as per your need.
score:27
i would prefer to use createasyncthunk
for api data with extrareducers
let assume this page name is productslice.js
import { createslice,createselector,payloadaction,createasyncthunk,} from "@reduxjs/toolkit";
export const fetchproducts = createasyncthunk(
"products/fetchproducts", async (_, thunkapi) => {
try {
//const response = await fetch(`url`); //where you want to fetch data
//your axios code part.
const response = await axios.get(`url`);//where you want to fetch data
return await response.json();
} catch (error) {
return thunkapi.rejectwithvalue({ error: error.message });
}
});
const productsslice = createslice({
name: "products",
initialstate: {
products: [],
loading: "idle",
error: "",
},
reducers: {},
extrareducers: (builder) => {
builder.addcase(fetchproducts.pending, (state) => {
state. products = [];
state.loading = "loading";
});
builder.addcase(
fetchproducts.fulfilled, (state, { payload }) => {
state. products = payload;
state.loading = "loaded";
});
builder.addcase(
fetchproducts.rejected,(state, action) => {
state.loading = "error";
state.error = action.error.message;
});
}
});
export const selectproducts = createselector(
(state) => ({
products: state.products,
loading: state.products.loading,
}), (state) => state
);
export default productsslice;
in your store.js
add productsslice: productsslice.reducer
in out store reducer.
then for using in component add those code ... i'm also prefer to use hook
import { useselector, usedispatch } from "react-redux";
import {
fetchproducts,
selectproducts,
} from "path/productslice.js";
then last part calling those method inside your competent like this
const dispatch = usedispatch();
const { products } = useselector(selectproducts);
react.useeffect(() => {
dispatch(fetchproducts());
}, [dispatch]);
and finally, you can access data as products
in your component.
Source: stackoverflow.com
Related Query
- Redux Toolkit and Axios
- confusion about `useSelector` and `createSelector` with Redux toolkit
- Redux saga, axios and progress event
- How can I cache data that I already requested and access it from the store using React and Redux Toolkit
- React observable epic with Redux Toolkit and Typescript
- Redux testing multipart/form-data with jest, nock, axios and jsdom
- A state mutation was detected between dispatches, Redux toolkit and selectors/reselect
- Adding an error state with Axios and Redux
- Returning promise object on GET API request by Redux and Axios
- Exported variable 'store' has or is using name '$CombinedState' from external module error Redux toolkit and redux persist
- createAsyncThunk redux toolkit with typescript rejecWithValue and Payload types error
- React Router Link with params not reloading page with new data from componentDidMount and Redux axios data fetching
- Typescript and redux toolkit
- SetState with react hook and redux after async call to axios API
- REACT How to make AJAX requests with Redux and Axios (with promise middleware)?
- Getting 'Object is of type unknown' in createAsyncThunk function after using Typescript and Redux Toolkit
- Configure reducers of connected-react-router and Redux Toolkit Query properly
- Dispatch with multiple parameters and create action with Redux Toolkit
- Getting status code 304 on a get request with axios using react and redux
- Post Data With Redux and Fetch API with Axios Get Error Result so Looping Response Pending
- how to check if a product is repeated in shopping card in redux toolkit and react js
- Redux toolkit using createAsyncThunk and typescript error handling
- Is it possible to use redux and axios in react component library?
- How to filter and delete an item by using redux toolkit
- cancel all subscriptions and asynchronous tasks in a useEffect cleanup function - Redux Toolkit
- React, Redux and Axios - trying to make API call
- React and Redux toolkit : loose the state when I want to use filter action
- react redux and thunks / axios / is not a function
- Redux toolkit and typescript
- Difference between createSelector and createDraftSafeSelector API in Redux Toolkit
More Query from same tag
- Flatbutton(Input handler) doesn't seems to work
- I need to click twice on ,the button to display the component
- How can I pass array to url
- Pass a relative image url to a Reactjs component from asp.net
- Map component: Cannot read property 'initialize' of undefined
- Flux calling actions with arguments managed in store
- how to add row to a table using ReactJS on button click
- react layout not looking well
- How to test hidden Text which has a toggle function by using testing-react-library?
- How to refactor code inside switch statement using react?
- Secure payment with paypal
- React TypeScript: (props: OwnProps) => Element' is not assignable to type 'FunctionComponent<{}>
- How to redirect after login to a UserProfile view
- Passing custom props to a react component using typescript
- redux mapDispatchToProps with chained arrow functions
- Apply onChange effect on a select option
- React draft wysiwyg - Can't able to type text in editor after clearing editorState
- how do i set programmatically checkbox property 'checked' or 'defaultChecked' in react
- How to implement your own useMemo from Scratch, for React
- Real time update with ReactJS, Redux and Websocket
- How to know array contents are empty
- Rendering while cycling through object isn't working
- Problem with POST request from React.js component to Node.js server
- ReactJS: access components inside component "parent"
- React Typescript event type for both interfaces MouseEvent and TouchEvent
- How do you set the document title in React?
- React + Three-Fiber Instances Not Being Displayed
- Wrapping a component with itself in React?
- How can I restrict whole page to re-render in React?
- I need to show a react material ui confirmation dialog box or a sweet alert confirmation dialog box in handlesubmit function