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

191
Visualizações
How to change the data stored in LocalStorage when clicking on element in react?

I am creating to-do app in react, and storing the data in localstorage,when user click on particular task it is mark completed, for that purpose i have "complete" boolean property for all task in localStorage.now i want to change that property onclick of that particular task,How to achieve this?.Here is the code link : https://github.com/Khatri-Jinal/react-app/tree/practical4

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

0

get the value from local storage and update it and then set it again for ex: let data=localStorage.getItem('tasks') //make changes in data localStorage.setItem("tasks", JSON.stringify(tasks));

about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest you make a custom hook for local storage (ie. useLocalStorage). This ensures that when you update a value in the local storage, the components that are using the updated value are automatically re-rendered.

You may look it up online or use this youtube viode for your reference. The first example there is useLocalStorage.

EDIT: Your task variable should be an array of object. When rendering the task, pass an id or anything unique to the task on the onclick function (In this example, I'll just use task name but I advise to create your own).

// tasks hook
const [tasks, setTasks] = useState([
  {desc: 'jog', isComplete: true},
  {desc: 'walk', isComplete: false},
  {desc: 'read', isComplete: true},
]);

// rendering tasks
tasks.map(task => {
  <div key={task.desc} onClick={() => onClickTask(task.desc)}
    task.desc
  </div>
});

And this is your onClickTask function

const onClickTask = (identifier) => {
  const index = tasks.findIndex(task => task.desc === identifier);
  const newTasks = [...tasks];
  newTasks[index].isComplete = true;

  setTasks(newTasks);
};
about 4 years ago · Juan Pablo Isaza Relatório

0

I made this solution, I hope it helps.

  const [todoList, setTodoList] = useState([]);

  // Get todo list from localStorage when the component is mounted
  useEffect(() => {
    setTodoList(JSON.parse(localStorage.getItem('todoList')));
  }, [])

  function updateTodo(todoId, data) {
    const todoIndex = todoList.findIndex(todo => todo.id === todoId);
    // Get a copy of the todo
    let updatableTodo = { ...todoList[todoIndex] };

    // Update the todo here...
    updatableTodo.title = data.title;

    // Update the state and localStorage
    setTodoList(todoList => {
      const newTodoList = [...todoList];
      newTodoList[todoIndex] = updatableTodo;
      localStorage.setItem('todoList', JSON.stringify(newTodoList));
      return newTodoList;
    })
  }

  return (
    <div>
      {todoList.map((todo) => 
        <button onClick={() => updateTodo(todo.id, data)} key={todo.id}>Update</button>
      )}
    </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