G
G
Grione2021-10-11 11:16:03
React
Grione, 2021-10-11 11:16:03

How to get state via fetch?

Tell me, where is the mistake? I can't get data from the server correctly.
I am using jsonserver npm. Now [object Object], [object Object], [object Object] comes to my state, and accordingly everything falls. In this case, after the fetch, the console shows the correct array.
The json file looks like this:

{
  "notes": [
    {
      "id": 1,
      "title": "First note",
      "text": "first text",
      "tags": [ "movies", "books", "thoughts" ],
      "editing": false
    },
    {
      "id": 2,
      "title": "Second note",
      "text": "Second text",
      "tags": [ "goals" ],
      "editing": false
    },
    {
      "id": 3,
      "title": "Third note",
      "text": "Another one text",
      "tags": [ "goals", "soccer", "poker" ],
      "editing": false
    }
  ]
}


//action creators 
export const fetchNotes = () => {
  return async (dispatch) => {
    fetch('http://localhost:5000/notes/').then((res) => res.json()).then((json) => {
      console.log(json); // вот здесь нормальный массив
      dispatch({
        type:'loadNotes',
        payload: json
      });
    });
  };
};

// reducers
let initialState = [];

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'loadNotes':
      return [ ...state, action.payload ];

    default:
      return state;
  }
};

export default reducer;

// store
export const store = createStore(reducers, {}, applyMiddleware(thunk));

//index.js
ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

//app.js
const App = () => {
  const state = useSelector((state) => state.notes);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchNotes());
  }, []);

  console.log(`state: ${state}`);

  const [ showAddNote, setShowAddNote ] = useState(false);
  const [ tags, setTags ] = useState([]);

  // Get all tags
  const getAllTags = (notes) => {
    const newTags = new Set();

    if (notes.length) {
      console.log(`notes: ${notes}`)
      notes.map((it) => {
        console.log(`it: ${it}`); // А тут и далее [object Object],[object Object],[object Object]
        return it.tags.forEach((it) => newTags.add(it));
      });
    }

    return [ ...newTags ];
  };

  const filteredNotes = state.filter((note) => {
    return !tags.length || tags.find((item) => note.tags.includes(item));
  });

  //Sort notes
  const sortNotes = (checked, value) => {
    setTags(!tags.includes(value) && checked ? [ ...tags, value ] : tags.filter((n) => n !== value));
  };

  return (
    <div className="wrapper has-background-dark">
      <div className="container is-fluid">
        <div className="columns has-text-light">
          <div className="wrapper-column column has-background-dark">
            <AddNoteButton onAdd={() => setShowAddNote(!showAddNote)} isDisabled={showAddNote} />
            <TagsList tags={getAllTags(state)} onSort={sortNotes} />
          </div>
          <div className="wrapper-column column has-background-dark is-three-quarters">
            {showAddNote ? <AddNote onHide={() => setShowAddNote(false)} /> : ''}
            <NotesList notes={filteredNotes} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;


It all falls like this
6163f46183f61674347715.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-10-11
@Grione

case 'loadNotes':
  return [ ...state, ...action.payload ];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question