Search code examples
reactjsreact-nativereact-hookssanity

Unable to update the state in useState Hook


This is my code. I'm using sanity for content management and developing react native app. Here the API call is returning correct value however setdata is not updating the state services. So when I try to access this which is here <Text className="font-bold text-lg">{data.name}</Text> It gives error. Please help me solving this error. error log is mentioned below. I'm calling this component in another component like this `{request? : }' Main code.

import { StyleSheet, Text, View,Image, SafeAreaView } from 'react-native'
import React, { useEffect,useState } from 'react'
import { Octicons } from '@expo/vector-icons';
import { Pressable } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import client from '../sanity';

const Jobcard = () => {
    //console.log(data);
    const [services,setdata]=useState([]);
    useEffect(()=>
    {
        fetchdata();
    },[services]);
    
    const fetchdata=async()=>
    {
        try {
            const query=`*[_type == "service"]
            {accepter{_ref},requester{_ref},datetime,name,location,workhour}`;
           const response= await client.fetch(query);
              console.log(response);
              setdata(response);
              console.log(services);
        } catch (error) {
            console.log(error);
        }
       
    }
    const requestService=()=>{
        // service request code should come here
        console.log("setrvice requested");
    }
    const renderpage=({data})=>
    {
        

            <View>
                <Text className="font-bold text-lg">{data.name}</Text>  
                <Text className="font-bold">{data.location}</Text>
                <Text>Workling hours:{data.workhour}</Text>
                <View className="flex-row justify-center mt-3 space-x-6 items-center">
    
               
                <View className="bg-green-500 px-2 py-2 rounded-md">
    
                <Pressable className="" android_ripple={{color:"gray"}} onPress={requestService}>
                            <Text className="text-center text-white">Request Now</Text>
                </Pressable>
                </View>
                </View>
            </View>
            {/* image part */}
            <View>
                <Image source={{uri:data.url}} className="h-24 w-24 rounded-full "></Image>
            </View>
   
           
     
          
    }
  return (
    <SafeAreaView>
    <FlatList  data={services}
    renderItem={renderpage}/>
    </SafeAreaView>
  )
}

export default Jobcard

const styles = StyleSheet.create({})

In the useEffect I'm calling the function fetchdate(). The API call is successful and it returns this

 LOG  [{"accepter": {"_ref": "r7D6aPT0NrdX0UJBnRdPKr"}, "datetime": "2023-06-17T17:13:00.000Z", "location": {"_type": "geopoint", "alt": -2, "lat": 10.2365, "lng": 123.36}, "name": "Plumber", "requester": {"_ref": "d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4"}, "workhour": "9-11"}, {"accepter": {"_ref": "wTURNjP62fuXRm3qPkJlYb"}, "datetime": "2023-06-20T17:14:00.000Z", "location": {"_type": "geopoint", "alt": -3, "lat": 56.325, "lng": 12.56}, "name": "Nurse", "requester": {"_ref": "d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4"}, "workhour": "17-22"}, {"accepter": {"_ref": "wTURNjP62fuXRm3qPkJlYb"}, "datetime": "2023-06-22T17:15:00.000Z", "location": {"_type": "geopoint", "alt": -3, "lat": 12, "lng": 46.35}, "name": "Mechanic", "requester": {"_ref": "xnDGSrek1dgx2qitI95DEZ"}, "workhour": "9-12"}]

However, response is not updating. When I try to access the name property , It gives this error

TypeError: Cannot read property 'name' of undefined

I read some posts which suggested to use useEffect() which I'm already using. Help is very much appreciated.


Solution

  • you have to import FlatList from react-native instead.
    here you are using another component from another package it is not the same thing:

    import { FlatList } from 'react-native';
    

    you still need to use data?.example instead of data.example.
    also add a return statement in renderpage function just before <view>...</view>