React, how to return a value from function to component?

Hiroyuki Nuri

I want to do a basic if, else operation inside my component, for that I need to return a [boolean] after checking if the image loaded correctly or not.

export const Suggest = (props) => {
  function handleLoad(url) {
    let image = new Image();
    image.src = url;

    image.onload = function() {    
      return false;
    }

    image.onerror = function() {    
      return true;
    }
  }

  return (
    <div>
      { 
        props.state.suggestions.map((item, i) => 
          <div key={i}>
            <span>Boolean {i} = {handleLoad(item.image) ? 'True' : 'False'}</span>
          </div>
        )
      }
    </div>
  )
}

Unfortunately calling the function handleLoad(item.image) returns null.

How should I fix this problem?

mehmetseckin

The handleLoad function does not return anything, and will return undefined by default. The onload and onerror are assigned new functions.

Since you're loading an image (an asynchronous operation), there is no way to return the result synchronously. You will need to use promises, e.g.

function handleLoad(url) {
  return new Promise(function (resolve, reject) {
    let image = new Image();
    image.src = url;

    image.onload = function() { 
        resolve();
    }

    image.onerror = function() {    
        reject(new Error('Image loading failed'));
    } 
  });
}

Then, you can load your images on componentDidMount, and use the then callback to set your state accordingly:

// This is just a helper method to set the loaded
// flag and update the state for a given suggestion.
// Added it to avoid repeating ourselves.
setSuggestionLoaded = (suggestionIndex, isLoaded) => {
    let suggestions = this.state.suggestions;
    suggestions[suggestionIndex].loaded = isLoaded;
    this.setState({ suggestions: suggestions });
}

componentDidMount() {
    this.state.suggestions.map((suggestion, i) => {
        handleLoad(suggestion)
        .then(() => {
            setSuggestionLoaded(i, true);
        })
        .catch((err) => {
            setSuggestionLoaded(i, false);
        }));
    })
}

Then you can render your state, it will be updated when the loading operations finish or fail.

  return (
    <div>
      { 
        props.state.suggestions.map((item, i) => 
          <div key={i}>
            <span>Boolean {i} = {item.loaded ? 'True' : 'False'}</span>
          </div>
        )
      }
    </div>
  )

Another option to do this would be via plain old callbacks, e.g.:

function handleLoad(url, successCallback, errorCallback) {
    let image = new Image();
    image.src = url;

    image.onload = function() { 
        if(successCallback) successCallback();
    }

    image.onerror = function() {
        if(errorCallback) errorCallback(new Error('Image loading failed'));
    } 
}


componentDidMount() {
    this.state.suggestions.map((suggestion, i) => {
        handleLoad(suggestion,
            () => {                
                setSuggestionLoaded(i, true);
            },
            (err) => {
                setSuggestionLoaded(i, false);
            }
        );
    })
}

But I'd personally recommend the promises approach. I'd go even further and recommend you to read about the new async / await syntax which essentially is a pretty way to write promise-based asynchronous JavaScript.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to get a return value from a React component function prop?

React native How to return a value from a function to the component

Return value from react component

How to return a value from a function in react native

How to fix linter expected to return a value at the end of react function component?

How do I return a react component inline from a function?

How can I return a React.Component class from a function?

How can I return a React Component from a function and render it onClick?

How to get value from a react function within a react component

How can I pass a value from a function to any component in React?

Return value from saga to react component

How to get a return value from async function to a variable in React Native?

How to return value of variable from async JS function in React Native

How to return a Component using the function in react?

How to return value in component react typescript

(react-native) function from another component won't return my value

How to return value from this function?

How to return a value from a function

How to access state value from one component to other function(not component) which is in separate file? React js

When Mapping over a react component how and where can i call a function to return a property value in the same component file?

How to call external function which return the json and call from react another component?

How to return a value from a function if no value is found

How to return a component in React

TypeScript and React: Pass component in props and return it from a function

How to Call selector function from React Component?

How to get function from parent component in React

How to access state from a react function component?

how to call a function from another component in react

How to open a component from a function react native