简体   繁体   中英

Api is not hitting using react-redux

user.js

import React, { useEffect } from 'react';
import { fetchBlog } from '../../redux';
import { connect } from 'react-redux'

const Home = ({ blogData, fetchBlog }) => {
const { id } = useParams();
useEffect(() => {
    fetchBlog();
}, []);

return (
    <>
        <div className="container">
            <div className="col-lg-10">
                <h2> React CRUD Operation </h2>
            </div>
            <div className="col-lg-2">
                <Link to="/add" >
                    <button> Add Blog </button>
                </Link>
            </div>
            <table className="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Picture</th>
                        <th>Title</th>
                        <th>Short Description</th>
                        <th>Author</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {blogData.map((it) => {
                        return (
                            <tr key={it.id}>
                                <td> {it.id} </td>
                                <td> {<img src={it.pic} alt="not available" />} </td>
                                <td> {it.title} </td>
                                <td> {it.short_desc} </td>
                                <td> {it.author} </td>

                    })}
                </tbody>
            </table>
           
    </>
 )
}

const mapStateToProps = state => {
 return {
  blogData: state.blog
 }
}

const mapDispatchToProps = dispatch => {
 return {
    fetchBlog: () => dispatch(fetchBlog())
 }
}

 export default connect (
   mapStateToProps,
   mapDispatchToProps
 ) (Home)

userAction.js import axios from 'axios'

export const fetchBlog = () => {
return (dispatch) => {
dispatch(fetchBlogRequest())
axios
  .get('http://localhost:3001/api/blog/get')
  .then(response => {
    const blog = response.data
    dispatch(fetchBlogSuccess(blog))
  })
  .catch(error => {
    // error.message is the error message
    dispatch(fetchBlogFailure(error.message))
  })
  }
 }

export const fetchBlogRequest = () => {
 return {
  type: 'FETCH_BLOGS_REQUEST'
 }
}

 export const fetchBlogSuccess = blogs => {
  return {
   type: 'FETCH_BLOGS_SUCCESS',
   payload: blogs
  }
 }

 export const fetchBlogFailure = error => {
  return {
    type: 'FETCH_BLOGS_FAILURE',
    payload: error
   }
  }

user reducer.js

const initialState = {
 loading: false,
 blogs: [],
 error: ''
}

const BlogsReducer = (state = initialState, action) => {
 switch (action.type) {
    case 'FETCH_BLOGS_REQUEST':
        return {
            ...state,
            loading: true
        }
    case 'FETCH_BLOGS_SUCCESS':
        return {
            loading: false,
            blogs: action.payload,
            error: ''
        }
    case 'FETCH_BLOGS_FAILURE':
        return {
            loading: false,
            blogs: [],
            error: action.payload
        }
    default: return state
 }
}

export default BlogsReducer

rootReducer.js

  import  { combineReducers } from 'redux'
  import BlogReducer from './reducer/blog'

 const rootReducer = combineReducers({
  blog: BlogReducer
 });

 export default rootReducer

store.js

import { createStore, applyMiddleware } from 'redux'
import rootReducer from './rootReducer'
import thunk from 'redux-thunk';

const store = createStore(
 rootReducer,
 applyMiddleware(thunk)
);

export default store

index.js

export * from './actions/blog'

I am trying to fetch data using react-redux but API is not hitting. I am new to redux and just trying to make a project but API is not hitting using this. I don't know what I am missing I have also provided provider store in index.js. Any help will be appreciated

the thunk you made fetchBlog should return an async function(aka a function that return a promise)

you just missed the return

function fetchBlog(){
   return function(dispatch){

     dispatch(someAction());

     return axios.get()
            .then(() => {
                dispatch(setAction());
            })
            .catch(error => {
                dispatch(onErrorAction());
            });
   }
}

or you can use async/await functions

function fetchBlog(){
    return async (dispatch) => {
       try{
         dispatch(someAction());

         const res = await axios.get();

         dispatch(setAction({ res }));

       }catch(error){

         dispatch(onErrorAction());
       }
    }
}

add to that in dispatch to props function you don't need to call it with dispatch because the thunk-middleware understand action as function and it go execute it, so you just need to have a reference to the thunk itself and you are ready

const mapDispatchToProps = dispatch => {
 return {
    fetchBlog: fetchBlog
 }
}

or better, just use an object

const mapDispatchToProps = {
    fetchBlog: fetchBlog
}

or you can

const mapDispatchToProps = {
    fetchBlog
}

which is even simpler

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