Home > Software engineering >  Json.parse not returning correctly (React Native)
Json.parse not returning correctly (React Native)

Time:02-01

I'm practicing SecureStore in expo with a test project. It's console logging the array with the objects after I restart the app but it wont setObjects(parsed) - instead I get a error "Objects are not valid as a React child (found:object with keys {title,age}). If you meant to render a collection of children, use an array instead. "

I feel like I just missed a syntax thing somewhere, but I can't seem to find where I went wrong, can someone help me correct this?

const  [name, setName] = useState()
const  [object, setObject] = useState([])

const save = async() => {
  try {
    const jsonValue =  JSON.stringify([{title:name, age:20}])
    await SecureStore.setItemAsync("MyName", jsonValue)
    setObject(jsonValue)
  }catch (err) {alert(err)}
}

const load = async() => {
  try {
   const jsonValue = await SecureStore.getItemAsync("MyName")
   const parsed = JSON.parse(jsonValue)
   if(name !== null) {
    console.log(parsed)
    setObject(parsed)
  }

  }catch (err) {alert(err)}
}

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


  return(
    <View style={{flex:1, backgroundColor:"beige", alignItems: "center", justifyContent: "center"}}>
      <Text>Enter something here</Text>
      <TextInput
      style={{backgroundColor: "grey", width:300, height: 50, paddingHorizontal: 30,}}
      onChangeText={text => setName(text)}

      />
      <Button title="save" onPress={()=>save()}/>
      <Text>{name}</Text>
      <Text>{object}</Text>
    </View>
  )
}

CodePudding user response:

You're trying to render object inside <Text>. Replace <Text>{object}</Text> with <Text>{object?.title}</Text>

  •  Tags:  
  • Related