Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
TODOLIST Update in REACT

So I was trying to update the value I got by the Addlist and I tried this but this isn;t working. Also when I click on the '+' button without writing anything, an empty list is created. How should I stop it. I've attached a code below.

import React from "react";
import "./App.css";
import { useState } from "react";
import TodoList from "./components/TodoList";

function App() {
  const [input, setInput] = useState("");
  const [list, setList] = useState([]);
  

  const updateList = (e) => {
    
    setInput(e.target.value);
    
  };

  const AddList = () => {
    console.log("value added")
    setList((addValue) => {
      
        
        return [...addValue, input];
      
     
    });
    setInput("");
  };

  const updateItems=(id)=>{
     const newValue=[...list].map((newVal)=>{
       if(input.id===id){
         input.text='';
       }
       return newVal;
     })
     setList(newValue);
    
  }

  const deleteItems = (id) => {
    console.log("deleted");
    setList((addValue) => {
      return addValue.filter((element, index) => {
        return index !== id;
      });
    });
  };

  return (
    
    <div className="todo-app">
      <h1> Enter Anything</h1>
      <input
        type="text"
        placeholder="Add anything"
        value={input}
        onChange={updateList}
      />
      <button onClick={AddList}>+</button>
      <ul>
        {list.map((itemsvalue, id) => {
          return (
            <TodoList
              itemsValue={itemsvalue}
              key={id}
              onSelect={deleteItems}
              id={id}
               onUpdate={updateItems}
            />
          );
        })}
      </ul>
    </div>
  );
}

export default App;

Any kind of help would be appreciated. Also if I want to split this into multiple components is there a way to do.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When user clicks on the add button there is the check for empty String AddList method for ex:- User updates second index value, second position value will get updated.

const [input, setInput] = useState('');
const [list, setList] = useState([]);
const [index, setIndex] = useState(null);

const updateList = (e) => {
    setInput(e.target.value);
};

useEffect(() => {
    setList(list);
    console.log(list, '<>?');
}, [index]);

const AddList = () => {
    if (input.trim() !== '') {
        setList([...list, input]);
    }
    setInput('');
};

const updateValue = (index) => {
    console.log(list[index]);
    setIndex(index);
    if (list[index].trim() !== '') {
        setInput(list[index]);
    }
};

const UpdateList = () => {
    list[index] = input;
    console.log(list, 'before  <>?');
    setIndex(null);
    setInput('');
};

return (
    <div>
        <input type="text" placeholder="Add anything" value={input} onChange={updateList} />
        <button disabled={!index && !list.length === 0} onClick={AddList}>
            Add
        </button>
        <button disabled={input.trim() === ''} onClick={UpdateList}>
            Update
        </button>
        {list.map((m, index) => (
            <h1 style={{ border: '1px solid black' }} onClick={() => updateValue(index)}>
                {m}
            </h1>
        ))}
    </div>
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda