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
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'?"
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:
here is a complete code snippet