Home > Software design >  AsyncStorage issue in react native expo
AsyncStorage issue in react native expo

Time:12-05

I can't even tell you how many variations I have tried, tutorials and documentations that I have watched and read, I cannot transfer data from one page to another. Am using react native expo. I have this included in both pages: import AsyncStorage from '@react-native-async-storage/async-storage';.

This is the page I'm trying to set the data:

const ToyDetails = () => {
  const [savedName, setSavedName] = useState('')
  
  const addCart = async() => {
    setButtonText('ADDED TO CART!')
    try {
      await AsyncStorage.setItem('saved_name', savedName)
    }catch(error){
      console.log(error)
    }
  }
  return(
    <View>
      <Text value={savedName}>{name}</Text>
      #{name} is because I am importing the name from a FlatList item
    </View>
  )
}

And getting that data from another page:

const Cart = () => {
  const [savedName, setSavedName] = useState('')

  useEffect(()=>{
      getData()
    }, [])

  const getData = () => {
    try {
      AsyncStorage.getItem('saved_name')
      .then((value)=>{
        if(value!=null){
          setSavedName(value)
        }
      })
    }catch(error){
      console.log(error)
    }
  }

  return (
    <View>
      <Text value={savedName} onChangeText={(value)=>setSavedName(value)}>{savedName}</Text>
    </View>
  )
}

I can post other variations I have tried if asked, I've tried adding it into a list and importing the list in the second page, I've tried to JSON.stringify the value savedName first (and JSON.parse it), I even tried doing it in the same way I did for FlatList. I'm not even getting any error messages.

CodePudding user response:

in your ToyDetails.js while saving savedName is empty. i changed to name and able to get it on CartScreen https://snack.expo.dev/7ozHrsOBT check ToyDetails.j file

const addCart = async() => {
    setButtonText('ADDED TO CART!')
    try {
      console.log("savedName",savedName) //saved name is empty here 
      await AsyncStorage.setItem('saved_name', name)
    }catch(error){
      console.log('setitem didnt work')
    }
  }
  • Related