I have data from redux called targetFarm. targetFarm.children contains these array object data.
JavaScript
x
7
1
targetFarm.children = [
2
{name: 'pizza'},
3
{name: 'buger'},
4
{name: 'robster'},
5
{name: 'water'},
6
]
7
I want to put data in targetFarm.children into gyetong using useEffect and setgyeTong hooks. As an array object value like below
JavaScript
1
9
1
expecter answer
2
3
gyetong = [
4
{'pizza'},
5
{'buger'},
6
{'robster'},
7
{'water'},
8
]
9
But with my code it only takes one array.
JavaScript
1
2
1
gyetong = ["pizza"]
2
How can i fix my code?
JavaScript
1
19
19
1
const App = () => {
2
const { targetFarm } = useAppSelector((state) => state.farm);
3
4
const [gyetong, setgyeTong] = useState([]);
5
6
return (
7
<Container>
8
{targetFarm.children.map((item, index) => {
9
10
useEffect(() => {
11
setgyeTong([item.name])
12
}, [item]);
13
14
})}
15
16
</Container>
17
)
18
}
19
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:
JavaScript
1
12
12
1
const App = () => {
2
const { targetFarm } = useAppSelector((state) => state.farm);
3
4
const [gyetong, setgyeTong] = useState(
5
targetFarm.children.reduce((p, n) => {
6
p.push([n.name]);
7
return p;
8
}, [])
9
);
10
11
return <Container>{/* your code here */}</Container>;
12
};
By default gyetong will have the values
JavaScript
1
6
1
gyetong = [
2
['pizza'],
3
['buger'],
4
['robster'],
5
['water'],
6
]