Home > Mobile >  Key not defined - React array map
Key not defined - React array map

Time:01-14

I'm modifying some code to use React Query rather than useEffect - see new code using React Query below:

import axios from 'axios';
import { useQuery } from '@tanstack/react-query'

function MembersList() {
  const { data } = useQuery(["members"], () => {
    return axios.get('http://localhost:3001/members').then((res) => res.data)
  })

  return (
    <div className="List">
      {data?.map((value, key) => {
        return (
          <div className="member">
            <div key={member_id}> {value.forename} {value.surname}</div>
          </div>
        );
      })}
    </div>
  );
}

export default MembersList;

I'm getting an error that 'member_id' is not defined - arising from the row where I try and add 'member_id' as a key (see below).

Error Message

'Member_id' is the first field in the array, see below JSON from Insomnia:

JSON showing the 'member_id field'

The error is clearly telling me to define 'member_id' but I'm not sure how or where specifically to do that.

If I remove the 'key={member_id}' then the code compiles and runs, but throws a warning that "Each child in a list should have a unique "key" prop.".

I've reviwed many similar issues on Stack Exchange and React docs, but still can't see why my code isn't working.

CodePudding user response:

The thing you are getting back from the request is an object. An object can be thought of like a dictionary, you look up a word and it has a definition attached to it. member_id is just one of the words you can look up in this object. Right now, you don't specify what member_id is so javascript "thinks" it should be a variable that you defined, similar to data above. However, what you really want is the value of member_id that is present in the object. Therefore you should change it to value.member_id where value is one of the objects in your data list.

A visual way of thinking about it is like this

data = [{...}, {...}, ...];
value = data[0]; // this is what map is doing except for 0...N-1 where N is the length of your list
value;
> {...}
value.member_id;
> 1

Therefore, change your code to this:

import axios from 'axios';
import { useQuery } from '@tanstack/react-query'

function MembersList() {
  const { data } = useQuery(["members"], () => {
    return axios.get('http://localhost:3001/members').then((res) => res.data)
  })

  return (
    <div className="List">
      {data?.map((value, key) => {
        return (
          <div className="member" key={value.member_id}> // <<<
            <div> {value.forename} {value.surname}</div>
          </div>
        );
      })}
    </div>
  );
}

export default MembersList;

CodePudding user response:

use key={value.member_id} or key={key}

  • Related