I have data from redux called targetFarm. targetFarm.children contains these array object data.
targetFarm.children = [ {name: 'pizza'}, {name: 'buger'}, {name: 'robster'}, {name: 'water'}, ]
I want to put data in targetFarm.children into gyetong using useEffect and setgyeTong hooks. As an array object value like below
expecter answer gyetong = [ {'pizza'}, {'buger'}, {'robster'}, {'water'}, ]
But with my code it only takes one array.
gyetong = ["pizza"]
How can i fix my code?
const App = () => { const { targetFarm } = useAppSelector((state) => state.farm); const [gyetong, setgyeTong] = useState([]); return ( <Container> {targetFarm.children.map((item, index) => { useEffect(() => { setgyeTong([item.name]) }, [item]); })} </Container> ) }
Advertisement
Answer
For your information, you cannot the expected answer of gyetong you mentioned. I assume from the code, you want to have an array of array containing single item.
You can instead of this, directly do this:
const App = () => { const { targetFarm } = useAppSelector((state) => state.farm); const [gyetong, setgyeTong] = useState( targetFarm.children.reduce((p, n) => { p.push([n.name]); return p; }, []) ); return <Container>{/* your code here */}</Container>; };
By default gyetong will have the values
gyetong = [ ['pizza'], ['buger'], ['robster'], ['water'], ]