Mehdi Faraji
Mehdi Faraji

Reputation: 3846

How can I set an object to a constant and display the value in react?

This is the app component :

function App() {
    const [ url, setUrl ] = useState({});
    const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            console.log(res);
            setUrl(res.config.url);
        });
    };

    return (
        <div className="App">
            <button onClick={() => fetch()}>Click</button>
            {url.length ? url : null}
        </div>
    );
}

This actually works and it displays the url string which is https://jsonplaceholder.typicode.com/posts when I click the button on the page but What I really want to do is to set the res whole object to the url constant and then display the config.url like this :

const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            setUrl(res);
        });
    };

and then :

<button onClick={() => fetch()}>Click</button>
            {url.length ? url.config.url : null}

but it doesn't work and it also does not throw an error .

How can I set the whole res object to url constant and then display url.config.url when I click the button ?

Upvotes: 0

Views: 658

Answers (2)

Justin Boyle
Justin Boyle

Reputation: 32

url.config is undefined until the axios request is made. You need to check that url.config is not undefined, if true, display url.config.url, else null.

<button onClick={() => fetch()}>Click</button>
        {typeof url.config !== 'undefined' ? url.config.url : null}

Upvotes: 1

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

You should check length from url.config.url, in url length now is miossing

{url.config.url.length ? url.config.url : null}

Upvotes: 0

Related Questions