How to save json data displayed on simulator to local storage (React-native)

Viewed 695

I am using react-native and expo. I have two screen. When user clicks on first screen symbol such as

First screen:

A
acompany
B
bcompany

User clicks on A symbol. I fetch some json data for that symbol and display on my second screen, but I want that fetched data to be saved on the second screen. But right now if I go back to first screen(it has some json data such as symbol name A and what it stands for acompany etc as given above) and come back to second screen the data get disappeared. Is there any way to store my data of second screen to the local storage? I have comment the line in second class that I would like to store in local storage

My second class:

import React, { useState, useEffect } from "react";
import {
  TouchableWithoutFeedback,
  Keyboard,
  FlatList,
  TextInput,
  Button,
  Text,
} from "react-native";
import {
  StyleSheet,
  View 
} from "react-native";
import { useStocksContext } from "../contexts/StocksContext";
import { scaleSize } from "../constants/Layout";


export default function StocksScreen({ route }) {
  const { ServerURL, watchList } = useStocksContext();
  const [state, setState] = useState({
    myListData: [],

  });

  const { stuff } = route.params;


  renderWithData = () => {
    return fetch(`http://131.181.190.87:3001/history?symbol=${stuff}`)
      .then((res) => res.json())
      .then((json) => {
        setState({
          isLoaded: true,
          myListData: json,
        });


      });
  };




  useEffect(() => {
    renderWithData();

  }, [watchList]);


  let item = state.myListData.length && state.myListData[0];


 //that's the data I would like to save on local storage (movie)
 let movie = (
  <View  style={styles.text}>
   <Text style={styles.text} key={item.symbol}>
      {item.high}
    </Text>

    <Text style={styles.text} key={item.symbol}>
      {item.close}
    </Text>


  </View>
)


  return (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
    <View style={styles.container}>
      <Text style={styles.text}>bb</Text>
      <View>{movie}</View>

      </View>
        </TouchableWithoutFeedback>

   );
}



const styles = StyleSheet.create({
  text: {
    color: "black",
    backgroundColor: "white",
  },
});

Third class: Here I would like to save my data to local storage

import React, { useState, useContext, useEffect } from "react";
import { AsyncStorage } from "react-native";

const StocksContext = React.createContext();

export const StocksProvider = ({})


  const [state, setState] = useState([]);

  return (
    <StocksContext.Provider value={[state, setState]}>

    </StocksContext.Provider>
  );

}}

How can I store my second screen data to the local storage? Is there any way to do that? I have never done this before such as storing data locally. I even went through a couple tutorials and looked online, but couldn't figure out. Any help is appreciated.

2 Answers

To store data locally, you can use React Native AsyncStorage to fetch saved data: getItem(). Also you can use store function by Redux. When creating your Redux store, pass your createStore function a persistReducer that wraps your app's root reducer. Once your store is created, pass it to the persistStore function, which ensures your redux state is saved to persisted storage whenever it changes.store,

To store data locally, you have to use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.

    import React, { useState, useContext, useEffect } from "react";
    import { AsyncStorage } from "react-native";

    const StocksContext = React.createContext();

    export const StocksProvider = ({})


      const [state, setState] = useState([]);

      storeData = async () => {
      try {
        await AsyncStorage.setItem(
          'Your Key',
           state
        );
      } catch (error) {
        // Error saving data
      }
    };

   retrieveData = async () => {
      try {
        const value = await AsyncStorage.getItem('Your Key');
        if (value !== null) {
          // We have data!!
          console.log(value);
        }
      } catch (error) {
        // Error retrieving data
      }
    };     

      return (
        <StocksContext.Provider value={[state, setState]}>

        </StocksContext.Provider>
      );

    }}

for the detail follow this link : https://reactnative.dev/docs/asyncstorage

Related