Search code examples
javascriptreactjsreact-nativeasyncstorage

useEffect re-render different values making impossible build setting screen using async storage


i'm quite new to react-native, i'm trying to implementing a setting screen in my recipe search app. basically the user can choose different filter to avoid some kind of food (like vegan or no-milk ecc.), i thought to make an array with a number for each filter and then in the search page passing the array and apply the filter adding piece of strings for each filter. the thing is: useEffect render the array i'm passing with async-storage empty on the first render, it fulfill only on the second render, how can i take the filled array instead of the empty one?

const [richiesta, setRichiesta] = React.useState('');
    const [data, setData] = React.useState([]);
    const [ricerca, setRicerca] = React.useState("");
    const [preferenza, setPreferenza] = React.useState([]);
    let searchString = `https://api.edamam.com/search?q=${ricerca}&app_id=${APP_ID}&app_key=${APP_KEY}`;
    
    useEffect(() => {
        getMyValue();
        getPreferences(preferenza);
    },[])

    const getMyValue = async () => {
        try{
             const x = await AsyncStorage.getItem('preferenza') 
             setPreferenza(JSON.parse(x));
        } catch(err){console.log(err)}
    }

    const getPreferences = (preferenza) => {
        if(preferenza === 1){
            searchString = searchString.concat('&health=vegan')
        }
        else { console.log("error")}
    }

    
    
    //useEffect 
    useEffect(() => {
        getRecipes();
    }, [ricerca])

    //fetching data
    const getRecipes = async () => {
        const response = await fetch(searchString);
        const data = await response.json();
        setData(data.hits);
    }

    //funzione ricerca (solo scrittura)
    const onChangeSearch = query => setRichiesta(query);

    //funzione modifica stato di ricerca
    const getSearch = () => {
        setRicerca(richiesta);
    }


    //barra ricerca e mapping data
    return(
   <SafeAreaView style={styles.container}>

         <Searchbar
         placeholder="Cerca"
         onChangeText={onChangeSearch}
         value={richiesta}
         onIconPress={getSearch}
         />

this is the code, it returns "error" because on the first render the array is empty, but on the second render it fills with the value 1. can anyone help me out please?


Solution

  • i forgot to put the index of the array in

            if(preferenza === 1){
                searchString = searchString.concat('&health=vegan')
            }
            else { console.log("error")}
        } 
    

    thanks for the answer tho, have a nice day!