Guys how can I map the data here
CodePudding user response:
Please share the data details what you are getting in the response.
CodePudding user response:
first set result if success is true:
const [result, setResult] = useState([])
if (json.success) {
setResult([...json.result])
}
then map like this:
result.map(item => {
return (
<span>{item.description}</span>
)
})
CodePudding user response:
Just do this:
<>
{ (result?.result||[]).map(item => (
<span>{item.value}</span>
))
}
</>
Problem: As per your response data you are getting the result array inside the response JSON and you are setting this JSON into the result state variable. So basically you have result inside the result. So above I have tweaked your code to have result.result
instead of only result
.
CodePudding user response:
The initial result
state is not defined, so there's nothing to map from on the initial render cycle. Provide valid initial state.
const [results, setResults] = React.useState([]); // <-- defined and mappable
Additionally, it seems that you are not updating the result
state with the array from the response.
Response:
{
result: [
{
description: "PlayStation Store R50 Voucher ",
productCode: "317",
value: 50,
vendor: "Sony PlayStation"
},
{
description: "R1 - R2500 1Voucher Token",
productCode: "311",
value: 0,
vendor: "1Voucher"
}
],
status: "Success"
}
...
fetch(
" .... ",
{
method: 'GET',
header: {
Authorization: `Bearer ${token}`,
},
},
)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.json();
})
.then(data => {
setResults(data.result); // <-- save the `result` property
})
.catch(() => {
// handle any errors/rejections
});
The results
should be mappable now.
results.map(({ description, productCode, value, vendor }) => (
...JSX...
))
CodePudding user response:
You can just do the following:-
const [results, setResults] = useState([]);
{results.length > 0 && results.map((result,index) => ( <span>{result.value}</span>))}