ItzaMi
ItzaMi

Reputation: 367

Difficulties creating an action that fetches data with React Redux and axios

I've taken this weekend to learn Redux but I can't understand how I can make API calls using axios, Redux and Redux Thunk

I've deleted everything from this sample project so that there's only one action: the one from which I want to get my data.

Here's the link to my codesandbox

I'm sure I'm missing something incredibly easy but I can't figure out what it is. If someone could help me or point me in the right direction I would very much appreciate it

My reducer

const initialState = {
  data: [],
};

const reducer = (state = initialState, action) => {
  const newState = { ...state };

  switch (action.type) {
    case 'SOMETHING':
      newState.data = action.data;
      console.log(newState.data);
      break;
    default:
      newState;
  }
  return newState;
};

export default reducer;

My Action

import axios from 'axios';

export function someFunction() {
  return (dispatch) => {
    axios.get('https://api.pokemontcg.io/v1/types').then((response) => {
      dispatch({ type: 'SOMETHING', data: response.data });
    });
  };
}

My App.js

function App({ someFunction }) {
  return (
    <div className="App">
      <button onClick={someFunction}>Click Me</button>
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    data: state.data,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    something: () => dispatch(actionCreator.someFunction()),
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

Upvotes: 0

Views: 147

Answers (1)

OFRBG
OFRBG

Reputation: 1778

You were almost there! The problems is here:

const mapDispatchToProps = (dispatch) => {
  return {
    something: () => dispatch(actionCreator.someFunction()),
  };
};

You're telling redux to map dispatch actions to props called { something }. You need to either rename the prop to something or rename the map to someFunction.

const mapDispatchToProps = (dispatch) => {
  return {
    someFunction: () => dispatch(actionCreator.someFunction()),
  };
};

Upvotes: 2

Related Questions