2

I am a beginner at React. I fetch data in an application using (Laravel API) and manipulate it. But the data is only available within the function scope. How can I retrieve it outside the function and using it somewhere else? How it will be possible?

//Function to get data from API
var userId = localStorage.getItem("userid")
const OrderStoryIds = fetch(`${"/api/v1/order?user_id=" + userId}`,{
        headers:{
            Authorization: "bearer " + localStorage.getItem("token")
    }}).then((response) => response.json()).then((order) => {
        var record={};
        if(order !== null) {
            order.forEach(function (items, index) {
                record[items.story_id]= items.status    
            });
        }
    return record
});
const printOrderStoryId = (id) => {
    OrderStoryIds.then((result) => {
        console.log(result[id]);
        var isAlreadyPurchased = result[id] === 1? true: false;
        console.log(isAlreadyPurchased);
        return isAlreadyPurchased;
});
};

const StoriesShow = (props, { key }) => {
        return (
            <div className="col-md-4" key={key}>
//This is where I want to call the above function and use the result for further use/something
            <div className="image-prinze">
                <img src={require('../../../../../public/images/frontend/' + props.image)} alt="" />
                {printOrderStoryId(props.id)? (
                   <div className="button-prinze">
                        <a href={'/storydetail/' + props.id} className="btn btn-prinze">Mehr erfahren</a>
                </div>): 
                (<div className="button-prinze">
                <span className="btn btn-prinze">already purchased</span>
        </div>)}
            </div>
        </div>
    );
}

2 Answers 2

2

fetch() is asynchronous so you can't simply return the variable outside of the function scope. However, there are workarounds:

var myVar = null;

fetch('http://example.com').then(function(data) {
    myVar = data.myVar
});

// your render should run when variables change
render() {
    return (myVar ?? 'not fetched yet');
}

Make sure, that (as shown above) at initial render the value of myVar is null and is only filled on subsequent calls. So your render() method must not rely on myVar having a value.

Sign up to request clarification or add additional context in comments.

Comments

0
yourMethod = (event) => {
      event.preventDefault();
      fetch(`/route_to_your_method_api/${id}`)
        .then((resp) => resp.json())
        .then(function(data) {
          //posible loading
        })
        .catch(function(error) {
          console.log(error);
        });
      }

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.