0

I'm trying to map through some data that looks like this:

[
{
  "id": "cambridgeshire",
  "name": "Cambridgeshire"
},
{
  "id": "bedfordshire",
  "name": "Bedfordshire"
}
]

And display it as a list.

I'm getting the error of allAreas is undefined. I have a feeling its because of the JSON Object which I'm unfamiliar with.

On checking the state of allAreas it shows undefined.

Heres the code Ive tried

const Directory = () => {
  const [allAreas, setAllAreas] = useState([]);

  useEffect(() => {
    fetchAllAreasData().then((data) => setAllAreas(data));
  }, []);
  return (
    <div className='directory'>
      <ul>
        {allAreas.map((area) => (
          <li key={area.id}>{area.name}</li>
        ))}
      </ul>
    </div>
  );
};

To clarify this is an array of objects

7
  • 2
    The initial value of allAreas is an empty object useState({}). Use useState([]) Commented Feb 4, 2020 at 6:32
  • Ok I did that and now have the error allAreas is undefined. And Ive just checked the state of allAreas and it reads undefined. Commented Feb 4, 2020 at 6:37
  • can you please show a console.log of data returned from fetchAllAreasData? Commented Feb 4, 2020 at 6:39
  • [ { "id": "avon-and-somerset", "name": "Avon and Somerset" }, { "id": "bedfordshire", "name": "Bedfordshire" }, { "id": "cambridgeshire", "name": "Cambridgeshire" }, { "id": "cheshire", "name": "Cheshire Constabulary" }, { "id": "city-of-london", "name": "City of London" } ] Commented Feb 4, 2020 at 6:44
  • 1
    Hi @akhil, I'd like to clear this. No, an empty array wouldn't throw you an error when you try to map it. The problem here is the suppose to be an array of allAreas had turned into undefined. Because "undefined" have no map function. It threw an error Commented Feb 4, 2020 at 7:04

5 Answers 5

3

Make sure the allArea exists before mapping.

const Directory = () => {
  const [allAreas, setAllAreas] = useState([]);

  useEffect(() => {
    fetchAllAreasData().then((data) => setAllAreas(data));
  }, []);
  return (
    <div className='directory'>
      <ul>
        {allAreas && allAreas.map((area) => (
          <li key={area.id}>{area.name}</li>
        ))}
      </ul>
    </div>
  );
};

If your problem didn't fix, use the useReducer instead because of some react problems in useState with arrays in sometimes.something like this:

function reducer(state = [], action) {
 return action;
}

const Directory = () => {
  const [allAreas, dispatch] = useReducer(reducer, []);

  useEffect(() => {
    fetchAllAreasData().then((data) => dispatch(data));
  }, []);
  return (
    <div className='directory'>
      <ul>
        {allAreas.length > 0 && allAreas.map((area) => (
          <li key={area.id}>{area.name}</li>
        ))}
      </ul>
    </div>
  );
}; 
Sign up to request clarification or add additional context in comments.

Comments

0
const [allAreas, setAllAreas] = useState([]); // your defaulted state must be [] instead of {}

3 Comments

Ok I did that and now have the error allAreas is undefined.
It is probably the "data" response of your fetchAllAreasData. Have you tried checking that and confirm that it is an array object?
was that inside the "then" of fetchAllAreasData? Try this to check if you got a responsefetchAllAreasData.then((data) => console.log(data))?
0

Just change first line of the function to :

const [allAreas, setAllAreas] = useState([]);

Comments

0

It may be issue because your map function gets called before promise resolved and you get data.

To avoid this please check the length of 'allAreas' before iterating over it.

Also the intitial values assigned to 'allAreas' object instead of array. Change initial assignment to an array.

const Directory = () => {
  const [allAreas, setAllAreas] = useState([]);

  useEffect(() => {
    fetchAllAreasData().then((data) => setAllAreas(data));
  }, []);
  return (
    <div className='directory'>
      <ul>
        {allAreas.lenght && allAreas.map((area) => (
          <li key={area.id}>{area.name}</li>
        ))}
      </ul>
    </div>
  );
};

Comments

-1

try,

 <ul>
     {allAreas && allAreas.map((area) => (
         <li key={area.id}>{area.name}</li>
     ))}
 </ul>

1 Comment

Although this code might solve the problem, a good answer should also include what the code does and how it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.