0

Not used Preact before so I'm wondering whether this is just another quirk of the library. Though I'm trying to map an array of state as you normally would but it's just not outputting the <li> like I thought.

import { h, Preact, setState } from 'preact';
import { useEffect } from 'preact/hooks';
import style from './style.css';

const state = { todos: [], text: '' };

const submitTodo = (e) => {
 e.preventDefault(e);
 addItem();
}

const addItem = () => {
 state.todos.push(inputValue());
}

const inputValue = () => {
 const todoInput = document.querySelector('.todoInput');
 let inputItem = todoInput.value;
 return inputItem;
}

const ToDo = () => (
 <div class={style.todo}>
  <h1 class="title">ToDo</h1>
  <ul class="todoList">
  {state.todos.map((item, i) =>{
   <li key={i}>{item}</li>
  })}
  </ul>
  <form onSubmit={addItem}>
   <input type="text" placeholder="Add a todo item here..." class="todoInput" onInput={inputValue}/>
   <button type="submit" class="updateBtn" onClick={submitTodo}>Add Task</button>
  </form>
 </div>
);

export default ToDo;

I've checked that the code I wrote actually maps the state correctly (which it does via console log anywhere else) but inside the ToDo component it just won't map.

Hopefully someone can tell me what rookie error I'm making? I'd be very grateful if you could help me map out the state correctly in the <li>!

Harry
  • 360
  • 6
  • 19
  • You should not mutate state, use `setState(state.todos.concat(inputValue());)` instead. Also I'm not sure you should use querySelector but I don't use preact, Can't you just use the `event.target`? – HMR Oct 26 '19 at 21:15
  • Possible duplicate of [Wrong components rendered by Preact](https://stackoverflow.com/questions/42773892/wrong-components-rendered-by-preact) – Traveling Tech Guy Oct 26 '19 at 21:16
  • Where does that setState need to go? @HMR – Harry Oct 26 '19 at 22:05
  • Where you did the mutating push. – HMR Oct 26 '19 at 22:06
  • Can't get past the `Uncaught ReferenceError: setState is not defined` error, not sure how to even define it? Currently made `addItem()` this `setState(state.todos.concat(inputValue));` Wondering if it's because I'm not using a `class`? – Harry Oct 26 '19 at 23:30

1 Answers1

0

You need to make ToDo rerender after state change. Otherwise it will always show the initial state.

marzelin
  • 10,790
  • 2
  • 30
  • 49