How use AsyncStorage with React Native and hooks?

Viewed 5247

I'm using the react-native-community/react-native-async-storage lib. For instance, I tried to make something similar to React Web but it did not work

 const [list, setList] = useState([]);


useEffect(() => {
    AsyncStorage.setItem('list', JSON.stringify(setList));
 }, [list]);
2 Answers

Try this way

import AsyncStorage from "@react-native-community/async-storage";

export default function App(props) {

  const [list, setList] = useState([]);

  useEffect(() => {
    AsyncStorage.setItem('list', JSON.stringify(list)); <-- Not use "setList", use "list" here -->
  }, [list]);

}

setList is method which use to set/update list data

In react native, AsyncStorage is async in nature.

u need to add async/await in the function.

const [list, setList] = useState([]);


useEffect(async () => {
    await AsyncStorage.setItem('list', JSON.stringify(setList));
 }, [list]);
Related