简体   繁体   中英

pass data into component with 'let' keyword

I am trying to pass some data into my FlatList component after running a graphql query. If I hard-code data using const DATA it works. However, if I define two cases (successful query and unsuccessful query) and use let DATA , the variables aren't passed into the FlatList properly and they are always undefined inside FlatList component.

How can I fix this? How can I ensure that DATA is passed into the FlatList only after the query has been run?

For example, hard coded data like this works:

const DATA = [
  {
    id: '1',
    imageUrl: defaultUrl,
    name: 'Friend',
    vehicles: [],
    rating: 1,
    numberOfFriends: 3,
  }
];

But this doesn't (query works fine though):

let DATA;
 const { data, error } = useGetMyProfileQuery({
    onCompleted: () => {
      console.log('frineds', data.me.friends)
      DATA = data.me.friends.map(
        (item: {
            firstName: string;
            id: number;
            rating: number;
            vehicles: Array<Vehicle>;
            friends: Array<User>;
          
        }) => ({
          id: item.id,
          imageUrl: defaultUrl,
          name: item.firstName,
          rating: item.rating,
          //vehicles: item.vehicles,
          vehicles: [],
          numberOfFriends: item.friends.length,
        }),
      );
    },
    onError: ()=> {
          DATA = [
            {
              id: '1',
              imageUrl: defaultUrl,
              name: 'Friend',
              vehicles: [],
              rating: 1,
              numberOfFriends: 3,
            }
        }
  });

FlatList:

        <FlatList
          showsHorizontalScrollIndicator={false}
          data={DATA}
          horizontal={true}
          //scrollEnabled
          renderItem={({ item }) => (
            <WhitelistItem
              title={item.name}
              face={item.imageUrl}
              firstName={item.name}
              rating={item.rating}
              numberOfFriends={item.numberOfFriends}
              vehicles={item.vehicles}
            />
          )}
          keyExtractor={(item) => item.id}
        />

Edit:

I know about setStates but does this guarantee that every time the query re-runs, the data will be updated? Or do I necessarily have to use useEffect etc? In the past when I have used useStates, the data was often not updated automatically and kept giving old data so I was looking for an alternative way

you should use hooks or class based state in that case, as thats the only way to update your component to render new incoming data, there is also the option of force updating the component but that one is not reliable

using useState hook you can set DATA variable and rerender the component to fill the array

import React, {useState} from 'react'

const YourComponent = () => {

    const [DATA, setDATA] = useState([]);


    const { data, error } = useGetMyProfileQuery({
        onCompleted: () => {
          console.log('frineds', data.me.friends)
          let tmpData = data.me.friends.map((
              item: {
                firstName: string;
                id: number;
                rating: number;
                vehicles: Array<Vehicle>;
                friends: Array<User>;
              
            }) => ({
              id: item.id,
              imageUrl: defaultUrl,
              name: item.firstName,
              rating: item.rating,
              //vehicles: item.vehicles,
              vehicles: [],
              numberOfFriends: item.friends.length,
            }),
          );

          setDATA(tmpData)
        },
        onError: ()=> {
            tmpData = [{
                  id: '1',
                  imageUrl: defaultUrl,
                  name: 'Friend',
                  vehicles: [],
                  rating: 1,
                  numberOfFriends: 3,
            }]

            setDATA(tmpData)
        }
      });
}

Here, When you pass DATA to flatlist, it is not getting the values at that time. That's why you get the error while passing the DATA.

You should wait somehow until the DATA gets the required values. You can also bind the rendering of flatlist based on the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM