How can I make LINE #1 to work?
Cookie
function GetBrandData() {
var jsonData = "";
useEffect(() => {
async function getData5() {
const response = await fetch(variables.API_URL);
jsonData = await response.json();
alert(JSON.stringify({ jsonData }));
/* The line above shows the following output
{
"jsonData": [{ "id": 1, "name": "ASUS", "isSelected": false },
{ "id": 2, "name": "DELL", "isSelected": true },
{ "id": 3, "name": "HP", "isSelected": true },
{ "id": 4, "name": "Lenovo", "isSelected": false },
{ "id": 5, "name": "MSI", "isSelected": false }]
}
*/
}
getData5();
}, [])
return (jsonData);
}
<>
var listBrands = GetBrandData();
// LINE #1
{listBrands.map(brand => <div>{<input key={brand.id} type='checkbox' value= {brand.name} onChange={handleCpusCheckbox} />}{brand.name}</div>)};
</>
I am trying to loop thought objects come from db.
And I have tried some methods found online. But
it still does not work.
2
Answers
Few things that are not correct with your code.
Your code should look something like this.
Here useEffect is run when component mounts, it runs the function
getData5
and inside the function it sets the data to listBrands, this triggers rerender of the component and you will have your data this time and mapping the component will work as expected.Don’t think too complex, make it easy by merging this two diff function and component.
Array
as it is by destruct of complex response.use state to re-render component
to load new UI with new input(db response).