Reputation: 180
I am trying to add redux data into a component , and I am getting below issue in console.log when I try to check the redux data, could someone able to help me with this
my redux slice is below . please check the bolded line it seems its causing the issue not sure why it happens
import { createSlice } from '@reduxjs/toolkit';
import alladds from '../auth/ads.json'
export const addsSlice = createSlice({
name: 'adds',
initialState: {
alladds: alladds
},
reducers: {
addalladds: state => {
state.alladds = alladds
},
},
});
export const { addalladds } = addsSlice.actions;
export const selectAddSlice = state => state.addsSlice.alladds
export default addsSlice.reducer;
this is my react component
import React,{useState, useEffect} from "react";
import { useSelector } from 'react-redux';
import {selectAddSlice} from './features/auth/addsSlice'
const Addtocart = () => {
const selectAddSlice1 = useSelector(selectAddSlice);
const [alladd, setAlladds] = useState(selectAddSlice1)
useEffect(() => {
console.log(selectAddSlice + "ffffff")
},)
return (
<div>
{alladd.map((add) => (
<div key={add.id}>
<div> {add.addname}</div>
<div> {add.price}</div>
</div>
))}
</div>
);
};
export default Addtocart;
this is the json data which is in redux [ { "addname": "normaladd", "price": "23", "id": "1" }, { "addname": "advancedadd", "price": "50", "id": "2" }, { "addname": "premiumadd", "price": "100", "id": "3" }
]
Upvotes: 1
Views: 759
Reputation: 19813
You don't need to copy Redux Store data into React local state, you can directly use selectedAdds
anywhere in the component. The component will re-render whenever data in Redux Store is changed.
const selectedAdds = useSelector(selectAddSlice)
// This is not required
// const [alladd, setAlladds] = useState(selectedAdds)
useEffect(() => {
console.log(selectedAdds)
}, [selectedAdds])
// If you want to see this log, put selectedAdds in dependency array
// So that the Hook will run whenever selectedAdds is changed
return (
<div>
{selectedAdds.map((add) => (
...
But if you really need to copy Redux data into local state, you can use a useEffect
:
const [alladd, setAlladds] = useState([]) // Line 1
useEffect(() => {
setAlladds(selectedAdds)
// Set in State whenever selectedAdds is changed; Not
// just once at the Line 1 (as initial value of state)
}, [selectedAdds])
return (
<div>
{alladd.map((add) => (
...
Upvotes: 2