0

I'm looking to dynamically create a new component every time the user clicks a button.

export default function WorkoutCard({ children }) {
    const [workoutNum, setWorkoutNum] = useState([1]);

    const addSets = () => {
        setWorkoutNum(workoutNum.push(workoutNum.length + 1));
    };

    return (
        <View style={styles.card}>
            <AppText style={styles.exerciseHeader}>{children}</AppText>
            {workoutNum.map((num) => (
                <WorkoutTextInput workoutNum={num} />
            ))}
            <Divider></Divider>
            <Button title="Add set" style={styles.add} onPress={addSets} />
        </View>
    );
}

Basically, I'm trying to create an array which is also going to have the following values [1,2,3,4...] when the user clicks the button. But I'm getting the following error when I press the button - 'Undefined is not a function'.

Any tips on how I can fix this please?

1
  • Im not totally sure, but could you try change onPress={addSets} by onPress={addSets()} Commented Feb 8, 2021 at 22:48

1 Answer 1

2

Problem: push()

The problem is the method Array.push(). The method mutates the array and returns the length of the new array. It does not return the array itself.

setWorkoutNum(workoutNum.push(workoutNum.length + 1));

When you call this, you are changing your state from an array [1] to a number 2.

Solution: concat() or spread

You need to set your state to a new array. You can do this with spread notation [...state, newVal] or with Array.concat(). The concat method creates a new array and does not mutate the existing one.

setWorkoutNum(workoutNum.concat(workoutNum.length + 1));
setWorkoutNum([...workoutNum, workoutNum.length + 1]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.