1

I want to render the text 'Results!' and the name of the largestLikeResult from my getLargest() function.

    getLargest() { 
        var largestLikeResult = null
        var largerstLikeNum= 0 
        if(this.props.results!=null){
            //.map goes through every result
            this.props.results.map(i=> {
                console.log(i.name)
                this.state.resultsRef.child(this.replaceAll("."," ",i.name)).once('value',function(snapshot) {
                if(largerstLikeNum<snapshot.val().right)
                {   
                    console.log("new largest in town")
                    largerstLikeNum = snapshot.val().right 
                    largestLikeResult= i.name 
                    console.log(largestLikeResult)
                }
                }) 
            })
            return (
                <div>
                {largestLikeResult}
                </div>
                )


        }
        else {
            return null
        }
    }

    render(){ 
        return (
            <div>
            Results! 
            <h1>{this.getLargest()}</h1>
            </div>  
        ) 
    }  
}
export default DisplayResults

Currently, only Results! shows up on page and the name of the largestLikeResult shows up in the console, not page. Any quick changes I can add to render() to show the value of largestLikeResult?

Thanks in advance!

1 Answer 1

1

For a quick change, I think if you change from map to forEach it will work fine:

this.props.results.forEach(i => {

But I'd suggest to refactor getLargest() function into something similar to this:

getLargest() { 
    let largerstLikeNum = 0; 
    const { results } = this.props;
    const { resultsRef } = this.state;

    // Always return early
    if (!results || !Array.isArray(results)) {
      return null;
    }

    return (
      <div>
        {
          results.map(i => {
              return resultsRef.child(this.replaceAll('.', ' ', i.name)).once('value', snapshot => {
                if (largerstLikeNum < snapshot.val().right) {   
                    console.log('new largest in town');
                    largerstLikeNum = snapshot.val().right ;
                    return (
                      <div>{i.name}</div>
                    );
                }
                return null;
              }) 
          })
        }
      </div>
    );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.