Customizing React components based on API data

const LinkList = () => {
    const [links, setLinks] = useState([]);
    const url = 'http://localhost:5000/xyz';

    const hook = () => {
        console.log('effect');
        axios
            .get(url)
            .then(response => {
                if (response.data.message === 'No links found') {
                    setLinks(null);
                } else {
                    setLinks(response.data.links);
                }
            })
            .catch(err => console.log("couldn't fetch data", err))
    }

    useEffect(hook, []);

    return(
        <div>
            {links ? (
                <>
                    <p className=''> link list page </p>
                    <ul>
                        {
                            links.map((link, index) => <li key={index}> {link.link} </li>)
                        }
                    </ul>
                </>
            ) : (
                <p> No links were found. </p>
            )}
        </div>
    )
}

I want the above component to render a different message, based on the response from the api being called. For example, if the api returns: {'message': 'No links found'}, then I don't want to render the ul tag with links but want to render a p tag with a message saying that no links were found.

How can I make this happen?

Answer №1

It might be more effective to assess the length of the links array instead. If it happens to be empty, then no links were retrieved from the API.

{links.length > 0 ? (
   <ul>
      {links.map((link, index) => <li key={index}> {link.link} </li>)}
   </ul>
) : (
   <p>No links were found!</p>
)}

Answer №2

If we focus on this specific scenario, could it suffice to simply verify the length of your "links" state? You could display your message when the length is 0.

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

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, wh ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Facing a multitude of errors while transitioning from Material-ui version 0.10.1 to 0.17

We've encountered quite significant changes between these versions, requiring us to upgrade 40 libraries in order to update React.js. The biggest challenges seem to stem from material-ui. Unfortunately, we can't find any documentation on how to ...

managing static assets within a storybook monorepo

I have a lerna + yarn workspaces monorepo with multiple packages and components, each one containing its own /assets folder with static images: /packages      /component1             /assets ...

difficulty in accessing data from local Node.js server on devices connected to the network using a React frontend interface

My client application is running on localhost:3001 while my server application is on localhost:3000 The server is listening on 0.0.0.0:3000 Data loads normally on my Mac, but I encounter an issue when trying to retrieve data on mobile devices within the ...

Having trouble with a Reactjs Facebook login library - update the componentClicked function to be async

Currently, I am working on incorporating Facebook login into my React application using Redux. Within my loginUser.js file, the "FacebookLogIn" component appears as follows: <FacebookLogin appId="375026166397978" autoLoad={true} fields="name, ...

The XML information vanished during the transformation into JSON format

After converting XML to JSON using multiple conversion libraries, I noticed that the property name attributes and Item name attributes were lost. Why is this happening? Does anyone have suggestions on how I can modify my XML to make it more compatible for ...

Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "ReferenceError: $vAddress is not defined" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that add ...

Animate the parent form element using Framer Motion when the button within the form is clicked

I have recently started using Framer Motion and I must say, it's a game-changer for animating divs and creating page transitions. However, I am facing a challenge while trying to animate the parent <form> tag based on the toggle state of my form ...

What is the best location to store an environment file within a React-powered frontend application?

Within my React application, I have stored my firebaseConfig object in an environment file called ".env.local" within the src folder. However, I am encountering an error indicating that the API key cannot be found. How can I troubleshoot and resolve this ...

Entering a string into Angular

Within my function, I trigger the opening of a modal that is populated by a PHP file template. Within this template, there exists a div element containing the value {{msg_text}}. Inside my JavaScript file, I initialize $scope.msg_text so that when the mod ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Creating a shimmering glow for a dynamic AJAX div block in real-time

I created an Ajax code that retrieves results from a txt file in real time, which are then automatically displayed in a div block using the following lines: if (xmlhttp.responseText != "") { InnerHTMLText = xmlhttp.responseText + document.getElementBy ...

Best practice for executing two .save() operations in mongoose

I've been attempting to save to two different documents and models within the same function, but I keep encountering strange errors no matter what approach I take. It appears that for some reason, mongoose is not allowing this to work as intended. Cu ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...