Home > Mobile >  onPress Handler of a button updates the state but screen goes blank
onPress Handler of a button updates the state but screen goes blank

Time:09-26

I am learning react native and trying to build a todo app. In the code below, I have two useState hooks one for keeping track of what user enters and allTodo one for keeping track of all the todos to be rendered, also I'm using FlatList for rendering todos but when I submit the todo, the screen just goes blank and nothing appears again until I refresh it again. Also I'm testing the app on chrome by selecting a device in it. could that be a problem? Please let me know what the problem is. Code is below:

import React, { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  FlatList,
  TouchableOpacity,
  Button,
} from "react-native";

export default function App() {
  const [allTodos, setAllTodos] = useState(["a", "b"]);
  const [todo, setTodo] = useState("");

  const handleSubmit = () => {
    setAllTodos(allTodos.push(todo));
    setTodo("");
  };

  return (
    <View style={styles.container}>
      <Text>{todo}</Text>
      <Text>Todo: </Text>
      <TextInput
        style={styles.input}
        placeholder="E.g. Buy eggs"
        onChangeText={(val) => setTodo(val)}
      />
      <Button title="Add Todo" onPress={handleSubmit} />

      <FlatList
        data={allTodos}
        // keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <TouchableOpacity>
            <Text style={styles.item}>{item}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#FBF4E9",
    alignItems: "center",
    // justifyContent: "center",
    paddingTop: 20,
  },
  item: {
    marginTop: 24,
    padding: 30,
    backgroundColor: "pink",
    fontSize: 24,
    marginHorizontal: 10,
    marginTop: 24,
  },
  input: {
    borderWidth: 1,
    borderColor: "#777",
    padding: 8,
    margin: 10,
    width: 200,
  },
});

This is what it looks before submitting the todo: image before submitting the todo

Image after I submit it:

image of the screen after todo is submitted

Thank you

CodePudding user response:

Don't mutate state. In your handleSubmit function, you are mutating the state allTodos.

simply change your handleSubmit function to,

const handleSubmit = () => {
  setTodo('');
  const currentTodos = [...allTodos];
  currentTodos.push(todo);
  setAllTodos(currentTodos);
};

Also you might want to pass the value prop of TextInput as todo.

Check this Live Snack to see it in action.

  • Related