Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert and Inserting dict values into react hook's list

I am beginner in react and building simple react app and I am trying to set dict values into state’s list from API.

The data which is returning from API is

["Book_1", "Book_2", "Book_3"]

so I am trying to convert this data into dict and insert into list. like :-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "name": "Book_1"
  },
  {
    "name": "Book_2"
  },
  {
    "name": "Book_3"
  }
]

but When I try to insert into state then it is not converting into dict.

App.js

function App() {
   const [dictData, setDictData] = useState([]);

   useEffect(() => {
      axios.get("/fetch_from_db/").then((response) => {
          // ["Book_1", "Book_2", "Book_3"]

          setDictData(dictData => ({
             ...dictData,
             ...{"name": response.data}

          }))

      })
   })

   return (
        <div>
        </div>
    )
}

When I run the function then it is setting state like

{
    "name": [
        "Book_1",
        " Book_2",
        " Book_3",
    ]
}

But I am expecting it to be like

[
    {"name":"Book_1"},
    {"name":"Book_2"},
    {"name":"Book_3"},
]

I have tried many times but it is still not working, Any help would be much Appreciated.

>Solution :

The dictData is an array that contains objects, and not an a dictionary object. To add items to it, use array spread. To create the objects, use Array.map() to generate objects from the names:

setDictData(dictData => [
  ...dictData,
  ...response.data.map(name => ({ name }))
])

In addition, since the useEffects doesn’t have any dependencies, it would be called whenever you set the state, resulting in an infinite loop of added items.

You should probably set an empty dependencies (call one on mount), and replace the current state:

 useEffect(() => {
    axios.get("/fetch_from_db/").then((response) => {
      setDictData(response.data.map(name => ({ name })))
    })
 }, []) // not dependencies, call only on mount
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading