skip to Main Content

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


  1. Few things that are not correct with your code.

    1. useEffect should not be inside any function, it should be in the top level for the component. read this
    2. The component only renders once on mount if you don’t have any states that are changing, in your code listBrands will not make the component re render when data is fetched as you are not using it as state.

    Your code should look something like this.

    const MyComponent = () => {
      const [listBrands, setListBrands] = useState();
      const [loading, setLoading] = useState(true);
    
      async function getData5() {
        const response = await fetch(variables.API_URL);
        jsonData = await response.json();
        alert(JSON.stringify({ jsonData }));
        setListBrands(jsonData);
        setLoading(false);
    
            /* 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 }]
                }
                */
      }
    
      useEffect(() => {
        getData5();
      }, [])
    
      if (loading) {
        return <div>Loading...</div>;
      }
    
    
    // LINE #1
    return {listBrands.map(brand => <div>{<input key={brand.id} type='checkbox' value=  {brand.name} onChange={handleCpusCheckbox} />}{brand.name}</div>)};  
    </>
    }
    

    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.

    Login or Signup to reply.
  2. Don’t think too complex, make it easy by merging this two diff function and component.

    import React, { useEffect, useState } from 'react';
    
    function GetBrandData() {
    
        const [jsonData, setJsonData] = useState([]);
    
        useEffect(() => {
            async function getData5() {
                const response = await fetch(variables.API_URL);
                setJsonData(await response.json());
    
                /* 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.map(brand => <div>{<input key={brand.id} type='checkbox' value={brand.name} onChange={handleCpusCheckbox} />}{brand.name}</div>)}
            </>
        );
    }
    
    export default GetBrandData;
    
    1. make sure that after getting db response, data type of jsonData will keep remain Array as it is by destruct of complex response.
    2. you have to use state to re-render component to load new UI with new input(db response).
    3. handle your alert conditionally to don’t reload your project every time. it can create infinite loop.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search