Home > Net >  Convert and Inserting dict values into react hook's list
Convert and Inserting dict values into react hook's list

Time:10-09

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 :-

[
  {
    "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.

CodePudding user response:

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
  • Related