Master the integration of Flask API with React-Redux by effectively implementing axios

Hello everyone!

I am new to the world of React-Redux and I am currently working on a classification app using Flask API with ReactJS as the front-end. However, I am facing some issues when trying to call the API in Redux through the action file. The prediction result always shows "500 server error", even though I have tested the API in Postman and it seems to be working fine.

My main objective with this app is to extract information from the payload object and display the prediction result within the component based on the input text provided. I have been struggling with this for the past day and it's really confusing me. I am utilizing axios and promises to handle the API calls.

Any assistance or guidance on this matter would be greatly appreciated. I apologize if my question sounds silly or incorrect. Here is the output from the console:

Output console error

This is the contentAction.js file:

export const setPredict = content => ({
   type: PREDICT_CLASS,
   content 
})
export const savePredict = content => (

    (dispatch ) => {
        console.log("Predict...")
    dispatch({type: PREDICT_CLASS})
    const payload = content

    const contents = new Promise((resolve, reject) => {
        api.post('/predicts', payload).then((response) => {
            dispatch(setPredict(response.data.data))
            resolve({status: true})
        }).catch((e)=> {
            reject(e)
        })
    })

    return contents

 }
)

This is the contentReducer.js file:

import * as actions from '../actions/actionTypes'

const initState = {
    content: {},
    loading: false,
}

const contentReducer = (state = initState, action) => {
    switch (action.type) {
        case actions.PREDICT_CLASS:
            return {content: action.payload, loading: false}
        default:
            return state;
    }
}
export default contentReducer

container.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import {withState, withHandlers, compose, lifecycle} from 'recompose'
import classifierComponent from '../pages/contentPages'
import {savePredict} from '../../actions/contentActions'
import {bindActionCreators} from 'redux'

// state 
const mapStateToProps = (state) => ({
    content: state.content,
    predicts: state.predicts,
})

const mapDispatchToProps = dispatch => ({
   savePredict: bindActionCreators(savePredict, dispatch),
})

export default compose(
    connect(mapStateToProps, mapDispatchToProps),
    withState('contentValue', 'setContentValue', ''),
    withState('predicts', 'setPredicts', ''),
    withState('loading', 'setLoading', false),
    withHandlers({
        handleContent: props => (event) => {
            event.preventDefault()
            props.setContentValue(event.target.value)
        },
        onSubmit: props => (event) => {
            event.preventDefault()
            props.setLoading(true)
            props.setContentValue(event.target.value)
            props.setPredicts(event.target.value)
            props.savePredict(props)
        }
    }),
)(classifierComponent)

component.js

const contentPages = ({handleContent, contentValue, predicts, onSubmit, loading}) => {
    return (
        <>
            <Container>
                <h1>Let's Classified Content!</h1>
                <Form onSubmit={onSubmit}>
                    <TextArea 
                        placeholder='Tell us more' 
                        onChange={handleContent}
                        value={contentValue}
                        name="content"
                    />
                    <Button 
                        style={{marginTop: "20px"}} 
                        primary
                        type="submit"
                        disabled={loading}
                    >
                        {loading? 'Making Prediction' : 'Predict'}
                    </Button>
                </Form>
                <br/>
                <p>Predicted: {predicts}</p>
            </Container>
        </>
    );
};

contentPages.propTypes = {
    handleContent: PropTypes.func,
    contentClick: PropTypes.func,
    contentValue: PropTypes.string,
    predicts: PropTypes.string,
    loading: PropTypes.bool,
};

export default contentPages;

This is the expected interface: Interface

Please note that there should be an output displayed.

webUrl api

import axios from 'axios'

export default axios.create({
    baseURL: `http://127.0.0.1:5000/api`,
    headers: {
        'Access-Control-Allow-Origin': '*',
    },
    timeout: 10000,
});

this is index.js

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux'
import {createStore, applyMiddleware} from 'redux'
import rootReducer from './reducers/contentReducer'
import {BrowserRouter as Router} from 'react-router-dom'
import Routes from './routes/routes'
import thunk from 'redux-thunk'
const store = createStore(rootReducer, applyMiddleware(thunk))
ReactDOM.render(
  <Provider store={store}>
    <Router>
      <Routes/>
    </Router>
  </Provider>,
  document.getElementById('root')
);

Answer №1

It appears that there is an outstanding promise waiting to be fulfilled.

To handle this situation in the contentAction, you can implement a try/catch block as shown below


export const setPredict = data => ({
   type: PREDICT_CLASS,
   data 
})
export const savePredict = content => (

    (dispatch ) => {
        console.log("Predicting...")
    dispatch({type: PREDICT_CLASS})
    const payload = content

    const processContent = async () => {

      try{
const response = await  api.post('/predicts', payload)
       dispatch(setPredict(response.data))
}
catch(error) {
Throw error

}
    })
}

    return processContent

 }
)

Please pardon any issues with my formatting.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement redux-persist with a toolkit and next-redux-wrapper?

Having issues setting up redux-toolkit, redux-persist, and next-redux-wrapper in my configuration. I've been trying to make the redux state persist but it's not triggering the redux actions that are supposed to save the state to local storage. H ...

The absence of ellipses in Typography MUI is a glaring omission

I'm looking to truncate long text with an ellipsis, but it doesn't seem to be working. Is there something wrong with my code or how can we improve it? CODESANDBOX -----> CLICK HERE <Typography variant="body2" color="blac ...

Having issues with TypeScript while using Redux Toolkit along with Next Redux Wrapper?

I have been struggling to find a solution. I have asked multiple questions on different platforms but haven't received any helpful answers. Can someone please assist me? Your help is greatly needed and appreciated. Please take some time out of your bu ...

Error in React/Redux: props are undefined when using mapDispatchToProps

I am currently searching for information within a database using a react app. Within the actions.js file, I can see the response.data data when I utilize console.table. However, even after exporting, when attempting to display the information, the variabl ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Is there a way to stop Material UI from dulling the color of my AppBar when using dark mode in my theme?

When I use mode: "dark" in my Material UI theme, it causes the color of my AppBar to become desaturated. Switching it to mode: "light" resolves this issue. This is how my theme is configured: const theme = createTheme({ palette: { ...

Press the body to update state in React and close the dropdown

Seeking a solution for closing a dropdown menu when a user clicks outside of it or on another element? Consider the following code snippet written in React: var Hello = React.createClass({ getInitialState() { return { openDropdown: false ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Material UI checkbox claims to be uncontrolled

Currently, I am utilizing the Material UI kit for React to create dynamic Checkboxes by updating them from states. However, an error message stating "uncontrolled element" keeps appearing. this.state = { items : [{item: "item1", checked: false}, ...

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

The countdown timer resets upon the conditions being rendered

I have been using the 'react-timer-hook' package to create stopwatches for each order added to an array. The problem I encountered was that every stopwatch, across all components, would reset to zero and I couldn't figure out why. After a lo ...

Utilizing JWT tokens for administrative and user authentication

I'm currently working with a system utilizing SPA (React) and JWT authentication (Node JS). I am trying to figure out the best way to determine the role of each user on the client side (such as admin, operator, etc) in order to render the appropriate ...

An issue arises when trying to close and reopen a tab on Internet Explorer 11

I am encountering an issue with my React application. Whenever I use window.location = "url", Internet Explorer closes the developer tools if they are open and refreshes the page while displaying a dialogue message stating "A problem with the webpage cause ...

Update elements dynamically using JSX

I have an array called data.info that gets updated over time, and my goal is to replace placeholder rendered elements with another set of elements. The default state of app.js is as follows: return ( <Fragment> {data.info.map((index) =&g ...

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

Building a Dynamic Video Element in Next Js Using TypeScript

Is there a way to generate the video element in Next JS using TypeScript on-the-fly? When I attempt to create the video element with React.createElement('video'), it only returns a type of HTMLElement. However, I need it to be of type HTMLVideoEl ...

When the SVG icon is clicked, it will redirect to a different page

I'm trying to figure out how to add a href attribute to an SVG icon in order to redirect to another page when the icon is clicked. I've saved the SVG icon as a React Component, but I'm unsure of what steps to take next. import React from &ap ...

Is there a way to design a selector that focuses on one particular day of the week?

I am seeking to develop a week selector feature that only displays Mondays on the calendar. For example: January (2024): 1 8 15 22 29 February (2024): 5 12 19 26 and so forth... I came across the react-date-range library, but it doesn't seem to h ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

How to Eliminate Lower Borders from DataGrid Component in Material UI (mui)

I've been trying to customize the spacing between rows in a MUI Data Grid Component by overriding the default bottom border, but haven't had much success. I've experimented with different approaches such as using a theme override, adding a c ...