Home > other >  Trouble parsing and displaying AXIOS returned data
Trouble parsing and displaying AXIOS returned data

Time:07-26

I am working on a Reat Native app and I have called an API via Axios. I get back the response as expected however anything I try to extract the values fails with various errors.

This is the format of the response: (This is actually stored in response.data.homes.home) and is all the data i want from the request.

[{"id":"0002","url":"https://www.url1.com","name":"name1","f_name":"f name1","x_id":"23212"},{"id":"0001","url":"https://www.url2.com","name":"name2","f_name":"f name2","x_id":"43234"},{"id":"0001","url":"https://www.url3.com","name":"name3","f_name":"f name3","x_id":"32334"}]

The key would be x_id.

Tried: (undefined is not an object evaluating response.map)

 <View>
      {response.map((item, index) => (
        <Text key={index}>{item}</Text>
      ))}
    </View>

Tried: (undefined is not an object....)

 <FlatList
      data={JSON.stringify(response.data.homes.home)}
      renderItem={({ item }) => {
        return <Text>{item.name}</Text>;
      }}
      keyExtractor={(item) => item.x_id}
    />

All I am trying to do is simply display the returned values to the screen. What am i missing here?

CodePudding user response:

The function JSON.stringify converts a JavaScript object to a JSON string. The FlatList component expects a plain array for its data prop.

If response.data.homes.home is already an array as your questions suggests, then use this for the data prop directly.

data={response.data.homes.home}

If response.data.homes.home is a JSON string, use JSON.parse.

data={JSON.parse(response.data.homes.home)}

It might be advised to use a state for the data prop.

const [data, setData] = useState();

React.useEffect(() => {
    // load data
    setData(response.data.homes.home);
}, [])

...

<FlatList
      data={data}
      renderItem={({ item }) => {
        return <Text>{item.name}</Text>;
      }}
      keyExtractor={(item) => item.x_id}
    />
  • Related