skip to Main Content

I’m struggling to build an array with async storage in react native, all the tutorials and documents pages for async storage are very basic and don’t provide much information past setting an item and then getting it, I’m new to programming and this is my first project so I’m struggling quite a bit

const Body = ({ navigation }) => {
  const [WorkoutsName, setWorkoutName] = useState();
  const [WorkoutSets, setWorkoutSets] = useState();
  const [WorkoutReps, setWorkoutReps] = useState();
  const [WorkoutWeight, setWorkoutWeight] = useState();

  let workoutSlide = [
    {
      name: WorkoutsName,
      sets: WorkoutSets,
      reps: WorkoutReps,
      weight: WorkoutWeight,
    }
  ]

  const load = async () => {
    try {
      const name = AsyncStorage.getItem("WorkoutName");
      const sets = AsyncStorage.getItem("WorkoutSets");
      const reps = AsyncStorage.getItem("WorkoutReps");
      const weight = AsyncStorage.getItem("WorkoutWeight");
      setWorkoutName(name);
      setWorkoutSets(sets);
      setWorkoutReps(reps);
      setWorkoutWeight(weight);
      console.log(workoutSlide);
    } catch (error) {
      alert(error)
    }
  };

This is my attempt at creating an array so far but I keep getting an error on my emulator saying to create an array

const WorkoutTile = ({ navigation }) => {

  const [WorkoutsName, setWorkoutName] = useState();
  const [WorkoutSets, setWorkoutSets] = useState();
  const [WorkoutReps, setWorkoutReps] = useState();
  const [WorkoutWeight, setWorkoutWeight] = useState();

  const onSubmit = async () => {
    try {
      AsyncStorage.setItem("WorkoutName", JSON.stringify(WorkoutsName));
      AsyncStorage.setItem("WorkoutSets", JSON.stringify(WorkoutSets));
      AsyncStorage.setItem("WorkoutReps", JSON.stringify(WorkoutReps));
      AsyncStorage.setItem("WorkoutWeight", JSON.stringify(WorkoutWeight));

      navigation.navigate("Body");
    } catch (error) {
      alert(error)
    }

This is my workout page where I set the data with a text input, I want it similar to a ToDo list where I add a workout with the name, sets, reps and weight and that then creates a tile on the main page to display that data

At the moment when I set the data, it changes the data I originally input but only once I’ve reloaded the app with expo but I want it to add a new tile each time I add a new workout, I just can’t seem to wrap my head around arrays

2

Answers


  1. Chosen as BEST ANSWER

    const Workout = ({ navigation }) => {
    
      const [WorkoutsName, setWorkoutName] = useState();
      const [WorkoutSets, setWorkoutSets] = useState();
      const [WorkoutReps, setWorkoutReps] = useState();
      const [WorkoutWeight, setWorkoutWeight] = useState();
    
      const onSubmit = async () => {
        try {
    
          AsyncStorage.setItem("WorkoutName", JSON.stringify(WorkoutsName));
          AsyncStorage.setItem("WorkoutSets", JSON.stringify(WorkoutSets));
          AsyncStorage.setItem("WorkoutReps", JSON.stringify(WorkoutReps));
          AsyncStorage.setItem("WorkoutWeight", JSON.stringify(WorkoutWeight));
          navigation.navigate("Body");
        } catch (error) {
          alert(error)
        }
    
      };
      return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
          <View style={styles.Container}>
            <TextInput style={styles.textInput} maxLength={28} placeholder="Workout" onChangeText={value => setWorkoutName(value)}></TextInput>
            <TextInput style={styles.textInput} keyboardType="number-pad"
              maxLength={2}
              placeholder="Sets"
              onChangeText={value => setWorkoutSets(value)}></TextInput>
            <TextInput style={styles.textInput} keyboardType="number-pad" maxLength={2} placeholder="Reps" onChangeText={value => setWorkoutReps(value)}></TextInput>
            <TextInput style={styles.textInput} keyboardType="number-pad" maxLength={3} placeholder="Weight" onChangeText={value => setWorkoutWeight(value)}></TextInput>
            <View style={styles.button}>
              <TouchableOpacity onPress={onSubmit}>
                <Text style={styles.buttonText}>Add to Workout</Text>
              </TouchableOpacity>
            </View>
    
          </View>
        </TouchableWithoutFeedback>
      );
    };
    const Body = ({ navigation }) => {
      const [WorkoutsName, setWorkoutName] = useState();
      const [WorkoutSets, setWorkoutSets] = useState();
      const [WorkoutReps, setWorkoutReps] = useState();
      const [WorkoutWeight, setWorkoutWeight] = useState();
      const [prevSlides, setWorkoutSlides] = useState();
    
    
      const load = async () => {
        try {
          const name = AsyncStorage.getItem("WorkoutName");
          const sets = AsyncStorage.getItem("WorkoutSets");
          const reps = AsyncStorage.getItem("WorkoutReps");
          const weight = AsyncStorage.getItem("WorkoutWeight");
          setWorkoutName(name);
          setWorkoutSets(sets);
          setWorkoutReps(reps);
          setWorkoutWeight(weight);
    
          if (name && sets && reps && weight) {
            setWorkoutSlides((prevSlides) => [
              ...prevSlides,
              {
                name: name,
                sets: sets,
                reps: reps,
                weight: weight,
              },
            ]);
          }
          console.log(prevSlides)
        } catch (error) {
          alert(error)
        }
      };
    
      deleteWorkout = () => {
        AsyncStorage.removeItem("WorkoutName");
        AsyncStorage.removeItem("WorkoutSets");
        AsyncStorage.removeItem("WorkoutReps");
        AsyncStorage.removeItem("WorkoutWeight");
        setWorkoutName("");
        setWorkoutSets("");
        setWorkoutReps("");
        setWorkoutWeight("");
      };
    
      useEffect(() => {
        load();
      }, []);
    
    
      return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
          <View style={styles.bodyContainer}>
            <View style={styles.topItem}>
              <Text style={styles.workoutName}>WorkoutName</Text>
              <View style={styles.srwTitles}>
                <Text style={styles.workoutSets}>Sets</Text>
                <Text style={styles.workoutReps}>Reps</Text>
                <Text style={styles.workoutWeight}>Weight</Text>
              </View>
            </View>
            <View style={styles.workoutTile}>
              <TouchableOpacity onPress={deleteWorkout}>
                <View style={styles.topItem}>
                  <Text style={styles.workoutName}>{WorkoutsName}</Text>
                  <View style={styles.srwTitles}>
                    <Text style={styles.workoutSets}>{WorkoutSets}</Text>
                    <Text style={styles.workoutReps}>{WorkoutReps}</Text>
                    <Text style={styles.workoutWeight}>{WorkoutWeight}</Text>
                  </View>
                </View>
              </TouchableOpacity>
            </View>
            <View style={styles.bottomBar}>
              <View style={styles.modalWeight}>
              </View>
              <View style={styles.button}>
                <TouchableOpacity onPress={() => navigation.navigate("AddWorkout")}>
                  <View style={styles.addWrapper}>
                    <Text style={styles.addText}>+</Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </TouchableWithoutFeedback>
      );
    }

    These are my 2 pages, the setWorkoutSlides has an error message when I hover over it saying "Could not find name 'setWorkoutSlides'. Did you mean 'setWorkoutSets'?"


  2. It seems like you are on the right track with your attempt to create an array using AsyncStorage and update it in React Native. However, there are a few improvements and corrections needed in your code.

    You can use the spread operator to maintain the previous array of slides and add a new one to it. This way, the new slide will be appended to the existing array without overwriting the previous values.

    Below is a small snippet of the load function:

        const load = async () => {
        try {
          const name = await AsyncStorage.getItem('WorkoutName');
          const sets = await AsyncStorage.getItem('WorkoutSets');
          const reps = await AsyncStorage.getItem('WorkoutReps');
          const weight = await AsyncStorage.getItem('WorkoutWeight');
    
          if (name && sets && reps && weight) {
            setWorkoutSlides((prevSlides) => [
              ...prevSlides,
              {
                name: name,
                sets: sets,
                reps: reps,
                weight: weight,
              },
            ]);
          }
         } catch (error) {
          alert(error);
        }
       };  
    

    here is a complete code snippet

        import React, { useState, useEffect } from 'react';
    import { AsyncStorage, View, Text, TextInput, Button } from 'react-native';
    
    const Body = ({ navigation }) => {
      const [workoutSlides, setWorkoutSlides] = useState([]);
    
      const load = async () => {
        try {
          const name = await AsyncStorage.getItem('WorkoutName');
          const sets = await AsyncStorage.getItem('WorkoutSets');
          const reps = await AsyncStorage.getItem('WorkoutReps');
          const weight = await AsyncStorage.getItem('WorkoutWeight');
    
          if (name && sets && reps && weight) {
            setWorkoutSlides((prevSlides) => [
              ...prevSlides,
              {
                name: name,
                sets: sets,
                reps: reps,
                weight: weight,
              },
            ]);
          }
        } catch (error) {
          alert(error);
        }
      };
    
      useEffect(() => {
        load();
      }, []);
    
      return (
        <View>
          {/* Your JSX for rendering workout slides */}
        </View>
      );
    };
    
    export default Body;
    
    const WorkoutTile = ({ navigation }) => {
      const [WorkoutsName, setWorkoutName] = useState();
      const [WorkoutSets, setWorkoutSets] = useState();
      const [WorkoutReps, setWorkoutReps] = useState();
      const [WorkoutWeight, setWorkoutWeight] = useState();
    
      const onSubmit = async () => {
        try {
          await AsyncStorage.setItem('WorkoutName', WorkoutsName);
          await AsyncStorage.setItem('WorkoutSets', WorkoutSets);
          await AsyncStorage.setItem('WorkoutReps', WorkoutReps);
          await AsyncStorage.setItem('WorkoutWeight', WorkoutWeight);
    
          navigation.navigate('Body');
        } catch (error) {
          alert(error);
        }
      };
    
      return (
        <View>
          {/* Your JSX for input components and submission */}
        </View>
      );
    };
    
    export default WorkoutTile;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search