1

I have this state defined:

 constructor(props){
        super(props);

        this.state = {
            open: false,
            customers:[],
            customer:{},
            products:[],
            product:{},
            orders:[],
            order:{},
            newForm:true,
            phoneNumbererror:null,
            shop:this.props.salon,
            value:'a',
            showTab:'none',
            slideIndex: 0,

        };
    }

With the following function which contains a fetch, I recieve an array of objects with responseData:

getProducts(){
        fetch(
            DOMAIN+'/api/products/', {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({products:responseData})
                console.log("Console log de products responseData");
                console.log(responseData);
            })
            .catch(function(e) {
                console.log(e);
            });
    }

This function is called in componentDidMount:

componentDidMount(){
        this.getCustomers();
        this.getProducts();
    }

The JSON object obtained from the fetch and kept within this.state.products looks like this:

Array(72)
0:
brand:{_id: "592d3092f42d775da9d38063", name: "Moroccanoil", __v: 0, created: "2017-05-30T08:42:58.242Z", photos: Array(0)}
created:"2017-06-14T18:46:52.508Z"
description:"Aporta una flexibilidad excepcional y proporciona un look hidratado y mate. Aplica una cantidad igual a la punta del dedo de esta arcilla filtrada, emulsiona entre las manos y distribúyela por el cabello. La fórmula de la arcilla purificada aporta al cabello textura y un acabado ligero y mate, y el Mineral Oil Finishing. Complex le proporciona un aspecto sano."
images:["https://storage.googleapis.com/magnifique-dev/olaplex 3.jpg"]
line:"Pruebadelproductolargo"
name:"Nombremuylargoaversicabe"
price:400
profile:"Decoloración"
salePrice:0
sex:["Mujer"]
size:"100 ML"
stock:400
videos:[""]
__v:19
_id:"5941849ce4fa0c7442b0f885"
__proto__:Object

As shown previously in the fetch, with this line this.setState({products:responseData}) I can pass products to the table where I want name and price to be displayed:

<DataTables
     height={'auto'}
     selectable={false}
     showRowHover={true}
     columns={FAV_TABLE_COLUMNS}
     data={this.state.products}
     showCheckboxes={false}
     rowSizeLabel="Filas por página"
           />

The table called is:

const FAV_TABLE_COLUMNS = [
    {
        key: 'name',
        label: 'Producto'
    }, {
        key: 'price',
        label: 'Precio del producto'
    }
];

How can I filter the products to display only the favourite ones of the client?

All of the favourite products of the client are stored in this other object within the array favouritesProducts:

Array(22)
12:
app:{created: "2017-07-07T13:34:14.249Z"}
billingAddress:[]
cardLastNumbers:"5262"
cardSaved:"true"
created:"2017-06-30T09:51:59.869Z"
creditCard:
cardNumberSalt: 
expirationSalt:
email:"[email protected]"
eyebrowType:"Pobladas"
eyelashType:"Rectas"
favouritesProducts:
Array(1)
0:
"594186cee4fa0c7442b0f942"
length:1
__proto__:
Array(0)
favouritesServices:[]
hairColor:"Rubio"
hairState:"Dañado"
hairType:"Medio"
loginType:[]
nailPolish:"Semipermanente"
nailType:"Naturales"
name:"AngelFBMag"
payerSaved:"true"
phoneNumber:
pictures:[]
platform:undefined
salt:
sex:"Mujer"
shippingAddress:[{…}]
shop:{_id: "59108159bc3fc645704ba508", location: {…}, settings: {…}, customers: Array(0), __v: 0, …}
surname:"Marquez"
__v:13
_id:"59561f3f1d178e1966142ad7"
__proto__:Object

This object is obtained through this other function:

getCustomers(){
        fetch(
            DOMAIN+'/api/customers/shop/'+this.props.salon, {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) =>
            {
                return response.json();
            })
            .then((responseData) => {
                responseData.map(function (v) {
                    v.platform = v.app ? v.app.platform : null  })
                this.setState({customers:responseData})
                console.log(responseData);
            })
            .catch(function() {
                console.log("error");
            });
    }

Currently I can print all the products without a filter. The question is how can I filter the products that I obtain, with the favourite products of the client.

CAPTURE OF THE CURRENT SITUATION: ALL PRODUCTS BEING DISPLAYED

CAPTURE FOR MELEXANDRE

2 Answers 2

1

Make a new function getFavouriteProduct that would looks something like this

getFavouriteProducts() {
    fetch(all products)
    .then((response1) => {
        fetch(fav products)
        .then((resonse2) => {
            // filter response1 on the basis of response2
            this.setState({desiredState: desiredOutput})
        })
    })
} 

edit: You can to do this from a single function as well.

getEverything() {
    fetch(data_by_get_product)
    .then((response1) => {
        fetch(data_by_get_customer)
        .then((resonse2) => {
            // filter response1 on the basis of response2
            this.setState({states_changed_by_getProduct: response1})
            this.setState({states_changed_by_get_customer: response2})
            this.setState({desiredOutput: filteredOutput}}
        })
    })
} 
Sign up to request clarification or add additional context in comments.

4 Comments

So getProducts would be redundant with this new function, right?
Edited the answer accordingly
When I get the first response should I pass the data into JSON format with response.json()?
Everything you have written remains, just use nested fetch statements to acheive your goal
0

You should use filter & map:

isProductInFavorites(product) {
    // TODO: Return true if the current product is in the Customer's favorites
}

render() {
    const products = this.state.products
        .filter((product) => this.isProductInFavorites(product))
        .map((product) => [product.name, product.price])
    return (
        <DataTables
         height={'auto'}
         selectable={false}
         showRowHover={true}
         columns={FAV_TABLE_COLUMNS}
         data={products}
         showCheckboxes={false}
         rowSizeLabel="Filas por página" />
    )
}

I'm not sure if you need an array of data or an object, but if you need an object, the function should be (product) => {name: product.name, price: product.price}.

Also, I'd like to make sure you know that fetch need you to check the status of the response, like described in the Github Polyfill. And it might be better if the server managed a "favorite" status on each product before returning the list for getProducts.

13 Comments

So, should I avoid using a fetch function and use const products = this.state.products.map((product) => [product.name, product.price]) above my DataTable or am I misunderstanding you?
I think there is a misunderstanding. Your getProducts looks fine, and it seems it's working. I would just check the status as shown on my link to be sure the server has not returned an error. Your problem was that you wanted to only display the name & price in your products list. Using a map is the perfect case for this, without changing your fetching method.
But the point is not to get all my products but only the favourites of the client.
I might have misunderstood the question. Sorry. I think the best way is to make only one fetch, your server should manage the favorite status of each product before sending the response. If you can't, by the same way I used .map, you could use .filter on the products list and return true only if the product is in the favoriteProducts array.
I edited my answer with an example of the filter. I'm not sure where your getCustomers is called, but the function to know if a product is in the product favorites should not be too complicated once you already have the two lists.
|

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.