Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I display my API response message on my frontend UI with React?

I have an Upload component that after submitting and completing the request to my API, returns a message (from the backend) and I have a state const [data, setData] = useState(); that I am utilizing to store the message. I would like to know how I can display this message as an h1 or p element if it’s possible. I have done it previously before but this implementation is a bit different and I need help. Here is the message and the code below. enter image description here

Upload.jsx:

import '../../components/pages/styles/Uploads.css';
import {useEffect, useState} from 'react';
import {} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import axios from 'axios';
import authHeader from '../../services/auth-header';
import {useForm} from 'react-hook-form';
import {clearMessage} from '../../slices/messages';
const API_URL = 'http://localhost:8080/api/posts';

function Uploads() {
    const {user: currentUser} = useSelector((state) => state.auth);
    const [successful, setSuccessful] = useState(false);
    const {message} = useSelector((state) => state.message);
    const dispatch = useDispatch();
    const {
        register,
        handleSubmit,
        watch,
        formState: {errors},
    } = useForm();
    //console.log(watch('title'));

    const [file, setFile] = useState();
    const [title, setTitle] = useState();
    const [preview, setPreview] = useState(null);
    const [data, setData] = useState();

    useEffect(() => {
        dispatch(clearMessage());
    }, [dispatch]);

    const onAddImage = (file) => {
        window.URL.revokeObjectURL(preview);
        if (!file) return;
        setPreview(window.URL.createObjectURL(file));
        setFile(file);
    };
    const onSubmit = async () => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', title);
        console.log(file);

        axios
            .post(API_URL + '/upload', formData, {
                headers: {...authHeader(), 'Content-Type': 'multipart/form-data'},
            })
            .then((res) => setData(res.data));
    };

    return (
        <div className='page'>
            <div className='upload-card'>
                <div id='preview'>
                    <img
                        src={preview || require('../../assets/user-solid.jpeg')}
                        id='image'
                        alt='Thumbnail'
                        className='user-post'
                    />
                </div>
            </div>
            <div className='upload-container'>
                <div className='post-form-container'>
                    <p id='upload-form-label'>Hello, feel free to post an image!</p>
                    <form onSubmit={handleSubmit(onSubmit)} className='upload-form'>
                        <div className='panel'>
                            <div className='button_outer'>
                                <div className='btn_upload'>
                                    <input
                                        {...register('file', {required: true})}
                                        filename={file}
                                        onChange={(e) => onAddImage(e.target.files[0])}
                                        type='file'
                                        accept='.jpeg,.svg,.gif,.png'
                                        id='image-selection-btn'
                                        name='file'
                                    ></input>
                                    Choose your Art
                                </div>
                            </div>
                            {errors.file?.type === 'required' && (
                                <p className='alert alert-danger' id='file-error'>
                                    File is required
                                </p>
                            )}
                        </div>
                        <input
                            {...register('title', {required: true})}
                            type='text'
                            onChange={(e) => setTitle(e.target.value)}
                            className='form-control'
                            placeholder='Title'
                        />
                        {errors.title?.type === 'required' && (
                            <p className='alert alert-danger' id='title-error'>
                                Title is required
                            </p>
                        )}

                        <button type='submit' id='post-upload-btn'>
                            Upload Image
                        </button>
                    </form>
                </div>
        {/* need help here */}
                {data && (
                    <div className='form-group'>
                        <div
                            className={data ? 'alert alert-success' : 'alert alert-danger'}
                            role='alert'
                        >
                            {message}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

export default Uploads;

I used a message state before but I dont know how I can utilize it this time or if it is even necessary since it is already stored in data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

messages.js:

// This updates message state when message action is dispatched from anywhere in the application. It exports 2 action creators:

// setMessage
// clearMessage

import {createSlice} from '@reduxjs/toolkit';
const initialState = {};
const messageSlice = createSlice({
    name: 'message',
    initialState,
    reducers: {
        setMessage: (state, action) => {
            return {message: action.payload};
        },
        clearMessage: () => {
            return {message: ''};
        },
    },
});
const {reducer, actions} = messageSlice;
export const {setMessage, clearMessage} = actions;
export default reducer;

>Solution :

If replacing setData(res.data) with console.log(res.data) yields the message value you are expecting to render

{ message: 'File Upload Successful' }

then I think you have everything you need there in the data state.

{data && (
  <div className='form-group'>
    <div
      className={data ? 'alert alert-success' : 'alert alert-danger'}
      role='alert'
    >
      {data.message}
    </div>
  </div>
)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading