简体   繁体   中英

How do I display data from api using react and redux

Hello I'm having a hard time wrapping my head around on the use of React and Redux to access data from and API, can some one give me a bit of guidance, as of now I just would like to display the small piece of data in App.js to see how it works for now. Any help would be greatly appreciated thank you.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk'
import {reducers} from './reducers'
import App from './App';

const store = createStore(reducers, compose(applyMiddleware(thunk)));

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

App.js

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getData } from "./actions/actions";


const App = () => {
  const [title, setTitle] = useState(0);
  const [description, setDescription] = useState(0);
  const dispatch = useDispatch();

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



  return (
    <div className="App">
      <h1>Hello</h1>
      {/* {posts.map((post)=>(
        <h1>{post.title}</h1>
      ))} */}
      {/* Trying to display title and description */}
      <h1>{title.title}</h1>  
      <h1>{description.description}</h1>  


    </div>
  );
};

export default App;

Actions/actions.js

import * as api from "../api/index"


export const getData = () => async(dispatch) => {
    try {
        const {data} = await api.fetchData();
        
        dispatch({ type: 'FETCH', payload: data });
    } catch(error) {
        console.log(error.message);
    }
};

Reducers/data.js

export default (data = [], action) => {
  switch (action.type) {
    case "FETCH":
      return action.payload;
    default:
      return data;
        
  }
};

Reducers/index.js

import { combineReducers } from 'redux';


import data from "./data";

export const reducers = combineReducers({ data })

API

import axios from "axios";

const url = "http://localhost:5000/routes";

export const fetchData = () => axios.get(url);

Theres only one piece of data in the database right now which is Title and description.

You should try Redux Toolkit, it saves a lot of time in creating the actions and reducers. Also read about createAsyncThunk for fetching data using and RESTful API. Try this tutorial https://www.softkraft.co/how-to-setup-slices-with-redux-toolkit/ And take a look into the documentation https://redux-toolkit.js.org/api/createAsyncThunk

You're not referencing anything from your redux store in App.js. To call data from the store, you need to use the useSelecter hook.

And I'm assuming your code is incomplete? If not the useEffect hook is redundant here. So are the useDispatch and useState hooks.

Below is the edited code with redux toolkit. It is the recommended library for using redux currently. I've forgotten what I learned about actions and reducers.

I'm not sure how does your initial data in redux store looks like, but here goes.

App.js

import React from "react";
import { useSelector } from "react-redux";
import { getData } from "./actions/actions";


const App = () => {
  const {data} = useSelecter((state) => state)
  const dispatch = useDispatch();

  useEffect(() => {
   fetch("http://localhost:5000/routes")
    .then(res => {
      return res.json();
    })
    .then(data => {
     // dispatch to store
    })
   }, []);



  return (
    <div className="App">
      <h1>Hello</h1>
      {/* {posts.map((post)=>(
        <h1>{post.title}</h1>
      ))} */}
      {/* Trying to display title and description */}
      <h1>{data.title}</h1>  
      <h1>{data.description}</h1>  
    </div>
  );
};

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM