E
E
Elrock2021-02-12 10:04:47
React
Elrock, 2021-02-12 10:04:47

Where to get data for rendering in redux?

I also found the layout of todoList on redux on the Internet, I
remade it a little for readability
I have one question, where to get the data to draw a new todo?
the form has a dispatch action that is in the reducer, and as I understand it, the new todo is stored in the reducer, how can I get it from there, which in this case is ({ todos })? destructured reducer?
index.js

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducer from './reducers'
import App from './components/App'

let store = createStore(reducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

reducers/index.js
const ADD = 'ADD_TODO'
let nextTodoId = 0

export const actions = {
  add: (text) => ({type: ADD, text, id: nextTodoId++}),
}

const reducer = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ]
    default:
      return state
  }
}
export default reducer

addTodo.js
import React from 'react'
import actions from '../reducers'

let AddTodo = ({ dispatch }) => {
  let input
  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault()
          if (!input.value) {
            return
          }
          dispatch(actions.add(input.value))
          input.value = ''
        }}
      >
        <input
          ref={node => {
            input = node
          }}
        />
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}
export default AddTodo


and drawing a new todo
import React from 'react'
import Todo from './Todo'

const TodoList = ({ todos}) => (
  <ul>
    {todos.map(todo => (
      <Todo key={todo.id} {...todo}  />
    ))}
  </ul>
)
export default TodoList

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
user_of_toster, 2021-02-12
@Elrock

React and Redux-store are not aware of each other's existence by default, so you need to include the react-redux module.
Without a module - to get the data you need to do store.getState().todos to change the data store.dispatch(action). store must first be exported to index.js, and then imported into rendering a new todo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question