React-Typescript-useState issue

import Button from "./assets/components/Button";
import Alert from "./assets/components/Alert";
import UserInput from "./assets/components/ToDo";
import React from "react";
import { useState } from "react";

function App() {
  let myToDos: Array<string> = [];
  const [alertVisible, setAlertVisibility] = useState(false);
  const [toDos, setToDos] = useState(myToDos);
  const [inputValue, setInputValue] = useState("");

  const onChange: React.ComponentProps<"input">["onChange"] = (e) => {
    setInputValue(e.currentTarget.value);
  };
  const onClick: React.ComponentProps<"button">["onClick"] = (e) => {
    e.preventDefault;
    setToDos([...myToDos, inputValue]);

    setInputValue("");
  };
  return (
    <div>
      {alertVisible && (
        <Alert onClose={() => setAlertVisibility(false)}>My Message</Alert>
      )}
      <Button onClick={() => setAlertVisibility(true)}>Click Me!</Button>
      <UserInput />
      <div id="to-do">
        <form>
          <h1>To-do Tasks: </h1>
          <input id="inputTasks" value={inputValue} onChange={onChange}></input>
          <button type="submit" onClick={onClick}>
            Add Todo
          </button>
        </form>

        <ul>
          {toDos.map((each, index) => (
            <li key={index}>
              {each}
              <button>Delete</button>
            </li>
          ))}
        </ul>
        <>{inputValue}</>
      </div>
    </div>
  );
}

export default App;

When I click Add Todo , the

  • element got rendered for a second and disappeared. I don’t know what’s wrong with my code.

  • 1 Like

    Hello, firstly you don’t need the myToDos variable; you can manage it with an empty array in useState.

    const [toDos, setToDos] = useState<string[]>([]);
    

    Also you don’t need to button type="submit" you already using state to manage inputValue with onChange function, you can use button type="button" and related with this preventDefault doesn’t seem right.

    It should be like this;

    e.preventDefault();
    

    Because of this your page has been reload after toDos rendering inside to <ul> element correctly and they get dissapear.

    Also you can create and use a different component to show the <ul> element in the DOM using toDos.map. Additionally, you can add another condition to render it only if toDos has any elements.

    I hope this will help this situation, happy coding :slightly_smiling_face:.

    1 Like

    Thanks. Problem solved. It works when i change the type of the button to “button” while everything else remains the same. I started out with the array typescript you suggested but i changed because i thought it was an issue.

    Great :+1:. You’re welcome :slightly_smiling_face:

    This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.