Search code examples
reactjsreduxresponseapi-design

React/Redux obtaining response from API


I can't quite figure out how to obtain in my React front the same result I get from my api in Postman.

for context I send a json formatted call of this nature :

{
    "bagel": false,
    "pretzel": false,
    "curry": true,
    "wurst": "true",
}

and I recieve the same sort of thing :

{
    "bagelavailability": false,
    "pretzelavailability": false,
    "curryavailability": true,
    "wurstavailability": "true",
}

but no matter what I do I can't get to console.log the received API answer.

Here's my current actions.jsx :

function FirstCall(specs) {
    return (dispatch) => {
        const payload = CallOne.post(specs);
        payload.then((response) => {
            console.log(response); // undefined !!
            if (!response.ok) { // this if is entered but I guess null.ok is false by definition.
                dispatch(Notifications.error({ title: 'Message', message: 'error!' }));
            }
        });
    };
}

this is my call one code :

/* ************************************* */
/* ********       IMPORTS       ******** */
/* ************************************* */
import Api from './Api';

const Resource = Api.all('order');
Resource.init = (data) => {
    if (data) {
        const dataObj = JSON.parse(data);
        return {
            all: Resource.all,
            data() { return dataObj; },
            save(...args) {
                if (this.data()[Resource.identifier()]) {
                    return Resource.put(this.data()[Resource.identifier()], this.data(), ...args);
                }
                return Resource.post(this.data(), ...args);
            },
            one: Resource.one,
            url: Resource.url,
        };
    }
    return undefined;
};
/* ************************************* */
/* ********       EXPORTS       ******** */
/* ************************************* */
export default Resource;

and here's "API" :

/* ************************************* */
/* ********       IMPORTS       ******** */
/* ************************************* */
import 'whatwg-fetch';
import restful, { fetchBackend } from 'restful.js';

/* ************************************* */
/* ********       EXPORTS       ******** */
/* ************************************* */
export default restful('http://localhost:8080', fetchBackend(fetch));

Solution

  • Ok so below are the files setup I have to hack through the issue :

    The hack I found is to make a reducer for the first call even thought that shouldn't be necessary and via it's success handle grab the response check it out : (better solutions most welcome)

    /Redux/EventTypes.jsx :

    export default {
        FIRST_CALL: { type: 'FIRST_CALL' },
        FIRST_CALL_FULFILLED: { type: 'FIRST_CALL_FULFILLED' },
        SECOND_CALL: { type: 'SECOND_CALL' },
        SECOND_CALL_FULFILLED: { type: 'SECOND_CALL_FULFILLED' },
    };
    

    /Redux/Reducers/FirstCall.jsx :

    import EventTypes from '../EventTypes';
    
    const initialState = {
        Document: {},
    };
    
    export default (state = initialState, action) => {
        switch (action.type) {
            case EventTypes.FIRST_CALL_FULFILLED.type:
                return { ...state, Document: action.payload.body() };
            default:
                return state;
        }
    };
    

    /Redux/Reducers/SecondCall.jsx :

    import EventTypes from '../EventTypes';
    import actions from '../../Components/CardCollection/actions';
    
    const initialState = {
    };
    
    export default (state = initialState, action) => {
        switch (action.type) {
            case EventTypes.SECOND_CALL_FULFILLED.type:
                const test = action.payload.body();
                const val = test.map(data => data.data());
                actions.generateDocument(val);
                return state;
            default:
                return state;
        }
    };
    

    /Redux/Reducers/Reducers.jsx :

    import { combineReducers } from 'redux';
    
    import FirstCall from './FirstCall';
    import SecondCall from './SecondCall';
    
    
    const reducers = combineReducers({
        firstCall: FirstCall,
        secondCall: SecondCall,
    });
    
    
    export default reducers;
    

    /Common/Resources/FirstCall.jsx :

    import Api from './Api';
    
    const Resource = Api.all('firstcall');
    Resource.init = (data) => {
        if (data) {
            const dataObj = JSON.parse(data);
            return {
                all: Resource.all,
                data() { return dataObj; },
                save(...args) {
                    if (this.data()[Resource.identifier()]) {
                        return Resource.put(this.data()[Resource.identifier()], this.data(), ...args);
                    }
                    return Resource.post(this.data(), ...args);
                },
                one: Resource.one,
                url: Resource.url,
            };
        }
        return undefined;
    };
    
    export default Resource;
    

    /Common/Resources/SecondCall.jsx :

    import Api from './Api';
    
    const Resource = Api.all('secondcall');
    Resource.init = (data) => {
        if (data) {
            const dataObj = JSON.parse(data);
            return {
                all: Resource.all,
                data() { return dataObj; },
                save(...args) {
                    if (this.data()[Resource.identifier()]) {
                        return Resource.put(this.data()[Resource.identifier()], this.data(), ...args);
                    }
                    return Resource.post(this.data(), ...args);
                },
                one: Resource.one,
                url: Resource.url,
            };
        }
        return undefined;
    };
    
    export default Resource;
    

    /Components/CardCollection/SearchByType.jsx :

    import { connect } from 'react-redux';
    import actions from './actions';
    import SearchByTypeComponent from './SearchByTypeComponent';
    
    const SearchByType = connect(mapDispatchToProps)(SearchByTypeComponent);
    
    function mapDispatchToProps(dispatch) {
        return {
            firstCall: payload => dispatch(actions.firstCall(payload)),
        };
    }
    
    export default SearchByType;
    

    /Components/CardCollection/SearchByTypeComponent.jsx :

    import React, { Component } from 'react';
    
    const propTypes = {
        ExecuteAPIcall: React.PropTypes.func,
    };
    
    class SearchByTypeComponent extends Component {
    
        constructor(props) {
            super(props);
            this.state = {
            };
            this.generate = this.generate.bind(this);
        }
    
        generate() {
            const { ExecuteAPIcall} = this.props;
            const payload = {
                var1: false,
                var2: true,
                var3: false,
                var4: 'zert',
                var5: '',
                var6: '',
                var7: '',
                var8: '',
                var9: '',
            };
            ExecuteAPIcall(payload);
        }
    
        render() {
            return (
                <div>
                        <button onClick={this.generate}>Générer</button>
                    </div>
                </div>
            );
        }
    }
    
    SearchByTypeComponent.propTypes = propTypes;
    
    export default SearchByTypeComponent;
    

    /Components/CardCollection/actions.jsx :

    import types from '../../Redux/EventTypes';
    import FirstCall from '../../Common/Resources/FirstCall';
    import SecondCall from '../../Common/Resources/SecondCall';
    
    function ExecuteAPIcall(specs) {
        const payload = FirstCall.post(specs);
        return dispatch => dispatch({ ...types.FIRST_CALL, payload });
    
    }
    
    function ExecuteAPIcallPartTWO(response) {
    
        const payloadToPost = {
            var1: 'ohoy',
            var2: 'aaha',
            var3: 'ouhou',
            var4: response,
        };
        const payload2 = SecondCall.post(payloadToPost);
        payload2.then(
            () => dispatch =>
                dispatch(
    console.log('success!');
    }
    
    const actions = {
        ExecuteAPIcall,
        ExecuteAPIcallPartTWO,
    };
    
    export {actions as default};