Y
Y
Yzurgzd2020-06-15 11:37:43
React
Yzurgzd, 2020-06-15 11:37:43

Why doesn't output data(undefined)?

actions/apps.js

const API_URL = "http://127.0.0.1:8000";

export const getApp = (slug) => (dispatch) => {
  const url = `${API_URL}/api/apps/${slug}/`;

  axios
    .get(url)
    .then((res) => {
      dispatch({
        type: GET_APP,
        payload: res.data,
      });
    })
    .catch((err) => console.log(err));
};


reducers/apps.js
import { GET_APPS, GET_APP } from "../actions/types.js";

const initialState = {
  app: [],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_APP:
      return {
        ...state,
        app: action.payload,
      };
    default:
      return state;
  }
}


Sample
export class Detail extends Component {
  static propTypes = {
    app: PropTypes.array.isRequired,
    getApp: PropTypes.func.isRequired,
  };

  componentDidMount() {
    this.props.getApp(this.props.match.params.slug);
  }

  render() {
    return (
      <>
         <h1>{this.props.app.title}</h1>
      </>
}
const mapStateToProps = (state) => ({
  app: state.apps.apps,
});

export default connect(mapStateToProps, { getApp })(Detail);


I get all the data from the backend.
5ee73335238a2204987160.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Didenko, 2020-06-15
@Dasslier

Your initial state app is an array. On the first render, you ask the array for the title property. After that, componentDidMount should already be running. Remove getting title and it won't crash

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question