skip to Main Content

I have a service result like this:

object inside array inside object.

So, If I need to single data I can use response.data.data[0].id It is work.(Not dynamically.) But when I set the response.data.data on state state got an error. (object value.)

API POSTMAN result:

{
    "data": [
        {
            "id": 640191,
            "name": "x",
                             
         },
         {
           "id": 640194,
            "name": "y",
          }
        
    ]
  
}

I use this service a.js and I need the show list data on b.js

2

Answers


  1. You’re trying to set the entire response data to a state variable. If the response data is an array of objects, you should be able to set it to a state variable without any issues.

    const [data, setData] = useState([]);
    
    useEffect(() => {
      fetch('your-api-url')
        .then(response => response.json())
        .then(data => setData(data.data));
    }, []);
    

    data is a state variable that will hold the response data, and setData is the function to update it. The useEffect hook runs once when the component mounts, and it fetches the data from the API, converts the response to JSON, and then sets the data state variable to the data property of the response data.

    If you’re getting an error when trying to set the state, it might be because the response data is not in the format you’re expecting. You should check the actual structure of the response data to make sure it matches what you’re expecting. You can do this by logging the response data to the console:

    fetch('your-api-url')
      .then(response => response.json())
      .then(data => {
        console.log(data);
        setData(data.data);
      });
    

    If the error message mentions "object value", it might be because you’re trying to render the data array directly in your JSX, which you can’t do because JSX can’t render objects directly. You need to map over the array and render each item individually. For example:

    return (
      <View>
        {data.map(item => (
          <Text key={item.id}>{item.name}</Text>
        ))}
      </View>
    );
    

    This code maps over the data array and renders a div for each item, with the item’s name as the content. The key prop is set to the item’s id to give each item a unique key.

    Login or Signup to reply.
  2. You first need to fetch the data and store the response in the state, here’s a quick example:

    import React, { useEffect, useState } from 'react';
    import { View, Text, FlatList } from 'react-native';
    
    const MyComponent = () => {
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetchData();
      }, []);
    
      const fetchData = async () => {
        try {
          const response = await fetch('https://api.example.com/data');
          const jsonData = await response.json();
          setData(jsonData);
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };
    
      const renderListItem = ({ item }) => (
        <View style={{ padding: 10 }}>
          <Text>{item.name}</Text>
          <Text>{item.description}</Text>
        </View>
      );
    
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <FlatList
            data={data}
            renderItem={renderListItem}
            keyExtractor={(item) => item.id.toString()}
          />
        </View>
      );
    };
    
    export default MyComponent;
    
    1. The useEffect hook is used to trigger the fetchData function when the component mounts.

    2. The fetchData function uses the fetch function to make an HTTP GET request to the server endpoint (https://api.example.com/data) and retrieves the response data as JSON. The data is then set to the component state using the setData function.

    3. The component renders a View container with a FlatList component that takes the data array as the data source, the renderListItem function as the item renderer.

    4. Each item is rendered with a View containing Text components to display the name and description.

    Note: Don’t forget to add keyExtractor function to generate unique keys for each item.

    You can read about and play around with the FlatList component

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search