How can i pass the data from the response as a prop to a component?

Viewed 188

I'm trying to get the response from the API to the store in order to make it available for any component to use it. in this case, I would like to be able to use all the body from the response as a prop that can be passed to components in order to render its value

Any idea on what should I do to be able to get the data from the response and render it? maybe I'm missing one redux step?


Reducer

export default (state=[], action) => {
  switch (action.type) {
      case 'FETCH_CV' :
          return [...state, action.paylaod];
        default:
            return state;
        }



Action creator

import DiagnoseMl from '../Components/API/DiagnoseMl';

export const fetchCv= (formData) => async dispatch => {

    
       const response = await DiagnoseMl.post('/d', formData);
      
        dispatch({type: 'FETCH_CV', payload: response.data});


  };



React component

import React from "react";
import styled from "styled-components";
import {connect} from 'react-redux';
import {fetchCv} from '../Actions';
import Example from '../Components/ReactToPrint'


class DataList extends React.Component{

    state = {
 
        // Initially, no file is selected
        selectedFile: null

      };
      
      // On file select (from the pop up)
      onFileChange = event => {
      
        // Update the state
        this.setState({ selectedFile: event.target.files[0] });

       };
      
      // On file upload (click the upload button)

      onFileUpload = () =>{
      
        // Create an object of formData
        const formData = new FormData();
      
        // Update the formData object
        formData.append(
          "file",
          this.state.selectedFile
        );
      
        // Details of the uploaded file
        console.log(this.state.selectedFile);
      
        this.props.fetchCv(formData);
      
      };

      
 render(){
    return (
        <Container>  
        <Uploader>
          <input  id="uploadBtn" accept="application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document" type="file" onChange={this.onFileChange} />
          <button onClick={this.onFileUpload}>
          Cargar Archivo
          </button>
         </Uploader>
        ***<Example/>*** //i want to use the reponse in this component
      </Container>
)

 }

}

// our state object will have a prop called data, that contains all of the data return from the reducer

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

};

export default connect(mapStateToProps,{fetchCv})(DataList);


Store set up

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


import App from './App';


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


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

thanks in advance!

1 Answers

Write a function, called a selector, that takes the store's state as an argument and returns the specific value from the state tree you'd like to use. Then import and call redux's useSelector (wrapping your selector) to obtain the most current value. You can then print that value in your component's jsx or pass it into whatever lower component it fits.

Side note: I recommend it in your action method, instead of just dumping your response body into the payload, you more explicitly map the properties you're expecting from your response. In your reducer, also explicitly destructure the expected value(s). It will keep your code easier to follow.

Selector file:

export const mySelector = (state) => {
   // Calculate the value you want from state and return it here.
}

In your component file:

import { useSelector } from 'redux';
import { mySelector } from 'path-to-mySelector';

...
//Inside the component definition:
const someExpectedValueFromStore = useSelector(mySelector);
Related