Skip to content

Instantly share code, notes, and snippets.

@muhammadawaisshaikh
Created March 24, 2020 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhammadawaisshaikh/0bd51c748d7dd1393f30857db9250786 to your computer and use it in GitHub Desktop.
Save muhammadawaisshaikh/0bd51c748d7dd1393f30857db9250786 to your computer and use it in GitHub Desktop.
Making API calls in React using Redux-Thunk
// redux > actions > actions.js
export const GET_USERS = "GET_USERS";
import React from 'react';
import { connect } from "react-redux";
import {
GetUsers
} from "./app/redux/actions/taskAction";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
// making all API calls and store in the redux-store
this.props.GetUsers();
}
render() {
console.log("this.props.tasksss ", this.props.Loading);
return (
<div>
...
</div>
);
}
}
const mapStateToProps = state => ({
Loading: state.task.loading
});
const mapDispacthToProps = dispatch => {
return {
GetUsers: () => dispatch(GetUsers())
};
};
export default connect(
mapStateToProps,
mapDispacthToProps
)(App);
import React from 'react';
import { connect } from "react-redux";
import { AddUser } from "../../redux/actions/taskAction";
class Home extends React.Component {
constructor(props) {
super(props);
}
// creating new user using Redux-Thunk
addNewUser = () => {
let data = {
"name": "muhammad awais",
"job": "developer"
}
this.props.submit(
data
);
}
render() {
// getting users from redux store
console.log("this.props.Users : ",this.props.Users);
return (
<div>
...
</div>
);
}
}
const mapStateToProps = state => ({
Users: state.task.Users
});
const mapDispacthToProps = dispatch => {
return {
submit: (data) => {
dispatch(AddUser(data))
}
};
};
// export default withStyles(styles)(ProductList);
export default connect(
mapStateToProps,
mapDispacthToProps
)(Home);
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";
import './index.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/lib/integration/react";
import configureStore from "./app/redux/store/store";
let { store, persistor } = configureStore();
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>,
</BrowserRouter>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
// redux > reducers > reducers.js
import { combineReducers } from 'redux';
import TaskReducer from './taskReducer'; //add this line
const rootReducer = combineReducers({
task:TaskReducer //add taskreducer and name is task for future use.
});
export default rootReducer;
// redux > store > store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from '../reducers/index';
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
key: 'root',
storage: storage,
}
const middlewares = [thunk];
if (process.env.NODE_ENV === `development`) {
const { logger } = require(`redux-logger`);
middlewares.push(logger);
}
const persistedReducer = persistReducer(persistConfig, reducers)
export default () => {
let store = createStore(
persistedReducer,
applyMiddleware(...middlewares)
)
let persistor = persistStore(store)
return { store, persistor }
}
// redux > actions > taskAction.js
import {
GET_USERS,
} from "./actions";
export const GetUsers = () => {
console.log("GetUsers");
return dispatch => {
console.log("GetUsers dispatch");
axios.get(`https://reqres.in/api/users`)
.then(res => {
const persons = res.data;
dispatch({
type: GET_USERS,
users: response
});
})
};
};
export const AddUser = (params) => {
console.log("AddUser");
return dispatch => {
console.log("Add User dispatch");
axios.post(`https://reqres.in/api/users`, {params})
.then(response => {
console.log(response);
axios.get(`https://reqres.in/api/users`)
.then(res => {
console.log(res);
dispatch({
type: GET_USERS,
users: response
});
})
})
};
};
// redux > reducers > taskReducer.js
import {
GET_USERS,
} from "../actions/actions";
const INITIAL_STATE = {
Users: [],
loading : false,
};
export default (state = INITIAL_STATE, action) => {
// console.log("task reducer" , action);
switch (action.type) {
case GET_USERS: {
return {
...state,
Users: action.users,
loading: false
};
}
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment