0

I have a project setup in node, express as backend and react as frontend, In node i have written

JSON.stringify(`${some_value}`);

and it is saved in the database.

To fetch, I am using useEffect hook and axios.get to the records from the database and rendered in the jsx

Is the above method the an good practice ???

const [allProjects, setAllProjects] = useState([]);

useEffect(() => {
    ... Axios.get ... other code
    setAllProjects(result); // if successfull response store it in state

In the return I have the below code

return (
    ... other code
    {allProjects.map((value) => {
        ... other codes
        allProjects.responsibilites.map((value) => {
            return(
                <p>{value.role}</p>
            )
        })}

allProjects.responsibilities has

[{"role":"manager","name":"Test"},{"role":"manager","name":"Test 2"}]

I am getting TypeError: Cannot read property 'map' of undefined

deepak murthy
  • 411
  • 3
  • 6
  • 21
  • is `allProjects.map` an array or `allProjects.responsibilites.map`? you are mapping with of them – webcoder Mar 04 '21 at 05:00
  • Initially before you are rendering your value is null so map is coming as undefined. You can add condition like when allProjects has data then map. – Coder Mar 04 '21 at 05:02
  • you should check initial `useState` it should initialize to empty array like `const [.....] = useState([])` – Kalhan.Toress Mar 04 '21 at 05:02
  • allProjects is array of objects --- {{id: 12345, name:"project name", responsibilities: "[{"role":"manager","name":"Test"}, {"role":"manager","name":"Test 12"}]"} – deepak murthy Mar 04 '21 at 05:04
  • @Kalhan.Toress I have initialised the state to const [allProjects, setAllProjects] = useState([]); – deepak murthy Mar 04 '21 at 05:06
  • @deepakmurthy are you sure `result` in `setAllProjects(result);` working correctly? – Kalhan.Toress Mar 04 '21 at 05:09
  • @Kalhan.Toress i get this {{id: 12345, name:"project name", responsibilities: "[{"role":"manager","name":"Test"}, {"role":"manager","name":"Test 12"}]"} when i do console.log(result); which is setAllProjects(results); – deepak murthy Mar 04 '21 at 05:11
  • what am i missing ? – deepak murthy Mar 04 '21 at 05:35
  • @deepakmurthy You missed to spell this correctly `allProjects.responsibilites.map....` it should be `responsibilities` as per the console.log :) and your second map should be `value.responsibilites.map((value)` isn't it? – Kalhan.Toress Mar 04 '21 at 05:54
  • sorry for the typo -- map is not a function - project.responsibilities.map is not a function – deepak murthy Mar 04 '21 at 06:37

3 Answers3

1

You're getting the result as string as you've stored the data into database as string.

What's happening:

  1. Frist you have the .map() method as the initial state is an empty Array []
  2. And then when you're re-setting the state with setAllProjects(result), a string is being set which does not have .map() method. Hence you're getting the error!

Solution:

So you've to first parse the JSON with JSON.parse(result) while setting it to the state.

useEffect(() => {
    ... Axios.get ... other code
    setAllProjects(JSON.parse(result));
Imran
  • 440
  • 4
  • 15
0

Your setup looks great!

You just need to account for state not having any data while the API call is being made. You can return null/loader etc in this case.

Also make sure that you don’t set state until the API call is complete.

You also have a bug in your mapping - try this instead (also note the correct spelling of “responsibilities”):

return (
    ... other code
    {allProjects?.map((project) => {
        ... other codes
        JSON.parse(project.responsibilities)?.map((responsibility) => {
            return(
                <p>{responsibility.role}</p>
            )
        })}
JBallin
  • 8,481
  • 4
  • 46
  • 51
0

First you have to check if allProjects has value or not, if so, you will call map method. Here is when allProjects = [] already called the map method => error: Cannot read property 'map' of undefined

Limina
  • 1