Home > Enterprise >  How to concatenate string with JSON in react.js
How to concatenate string with JSON in react.js

Time:10-07

I am new to react and I am trying to do simple thing.

I am receiveng JSON data from BE which looks like this:

{"data":[{"id":"12345",
"name":"Blabla",
"otherName":"3300",
"completeDate":"2021-10-01T05:00:00.000 0000",   
"status":"Active",
"location":"572957393.pdf"}]}

Now the location is the place where the file is stored on server and I need to concatenate data.location with URL so when I will render it, instead of this, "572957393.pdf" I will see this "https://www.mypage.com/files/https572957393.pdf"

I reckon the best way is to use .map method in fetch class-method but I cant make it work

The fetch statement :

fetchData(params, id){
    axios({
        url:`/admin/${this.state.radioSelect}/detail`,
        method:'get',
        params
    }).then(resp => {
        //const updated = resp.data.map(location) => This is where I am trying to use .map method
        .then(resp => {
        if(resp.data.code == '200'){ 
            this.setState({
                pageSize:this.state.pagination.pageSize,
                records:resp.data.data,
                recordsTableSpin:false,
                recordsId:id,
            })
        }
    })
}

Can you please help me figure this one out ? Thanks.

CodePudding user response:

concatenate the URL where you want to show the file in the browser. you can use two different states (one for fileName and one for URL) so that you can concatenate them like using a template literal

${URL}${fileName}

or

URL   fineName

CodePudding user response:

If I've understood your question right I think you could do the following:

fetchData(params, id){
    axios({
        url:`/admin/${this.state.radioSelect}/detail`,
        method:'get',
        params
    }).then(resp => {
        if(resp.data.code == '200'){ 
            const updatedData = resp.data.data.map(element => ({
                ...element, 
                location: element.location   resp.data.location
            }))

            this.setState({
                pageSize: this.state.pagination.pageSize,
                records: updatedData,
                recordsTableSpin: false,
                recordsId: id
            })
        }
    })
}
  • Related