0

I'm new to reactjs. I could map the data from json API. My objective is when we save a number in contactlist, it should show the name in message list also. I want to create 2 fetch data i.e., messageData, ContactData that should compare the Phone numbers of message API and COntact API. If Phone number is same in contact API and Message API then it should return name otherwise it should return only phone number.

Contact json data would be like

[
    {
        "id": 1,
       "name": "ABC",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
    },

    {
        "id": 2,
       "name": "DEF",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
    }
]

Contact Component:

import React, { Component } from "react";
import { Grid, Header, Button, Icon } from "semantic-ui-react";
import { Link } from 'react-router-dom'

class ComponentList extends Component {
  state = {
    peopleData: []
  };

  componentDidMount() {
      fetch('./people.json')
        .then(response => response.json())
        .then(data => this.setState({ peopleData: data }));
  }

 pnum(num) {
        return num.replace(/^\D/g, "");
      }

  render() {
    const {peopleData} = this.state;
return(
<div>
 { peopleData.map(people =>
<Grid>
<Grid.Row key={people.id}>
<Grid.Column>
<Header>{people.name}</Header>
<span>{people.phone}</span>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Button trigger={<Link to={`/displayChat/${this.pnum(people.phone)}`}>
<Icon name='comment alternate outline' color='teal' /></Link>}/>
</Grid.Row>
</Grid>
 )}
</div>
);
  }
}

export default ComponentList;

Message API:

[
{
 "id": 1,
"phone": "+91 789654123",
"message": "Hello everyone",
    "isrespond": true,
},

{
"id": 2,
 "phone": "+91 123456987",
"message": "hi",
    "isrespond": false,

}
]

DisplayChat component:

fetchChat() {
const { phone } = this.props.match.params ;
fetch(`api/conversation/${phone}`)
.then(response => response.json())
.then(data => this.setState({ messageList: data})
);
}

render(){
    const {messageList} = this.state;
    const { phone } = this.props.match.params ;
       return(
        <div>
          <ViewHeader phone={this.props.match.params}/>
        <Container className="viewMessage ">
        {messageList.map(data =>
        <Grid>
  <Grid.Row key={data.id}>      
    <p>{data.message}</p>
    </Grid.Column>     
  </Grid.Row>          
</Grid>
)}
</Container>
          <TypeHere phone={this.props.match.params}/>
</div>
    );
        }
        }

Can anyone help me in this?

Chandan
  • 25
  • 8
  • 1
    have you written any code? Please provide some working code and where exactly you are facing the issue. – Nilesh Jain Dec 11 '19 at 05:50
  • You can use Promise.all() or async/await for making a parallel calls and wait for both the results to come and then proceed with further statements. i don't if this link will help you but still you can take a look at it https://stackoverflow.com/questions/30823653/is-node-js-native-promise-all-processing-in-parallel-or-sequentially and https://itnext.io/node-js-handling-asynchronous-operations-in-parallel-69679dfae3fc – Nilesh Jain Dec 11 '19 at 05:54
  • Please paste a minimal sample of your code to get help. And I don't think this comes under reactjs. It goes into core javascript. – Vineeth Sai Dec 11 '19 at 05:58
  • @NileshJain - I've updated the code. Could you please see the functionality? – Chandan Dec 11 '19 at 06:27
  • 1
    @VineethSai - I apologize for not providing relevant code. I've updated the code. Could you please see the functionality? – Chandan Dec 11 '19 at 06:56

1 Answers1

0
   const URL1= "contactApi"

   const URL2= "messageApi"

I have used promise.all along with fetch to resolve both the endpoints

   Promise.all([
  fetch(URL1),
  fetch(URL2),
]).then(responses => responses
  ).then(responses => Promise.all(responses.map(r => r.json())))
.then(data=>writeLogic(data));


function writeLogic(data){
  let nameOrPhone;
  const contactApiData = data[0]
  const messageApiData = data[1]
  let isPresent
  for(let m of messageApiData){
    isPresent=false
      for(let c of contactApiData){
    if(m.phone === c.phone){
      isPresent=true
      nameOrPhone.push(c.name)
    }
  }
    if(!isPresent){
      nameOrPhone.push(m.phone)
    }
  }
  //update your state here if you are using React
  //this.setState({nameOrPhone})
  console.log(nameOrPhone)
}

data will contain result of both the endpoint in an array. you can use the data and write your logic on top of it.

Ref: https://javascript.info/promise-api

Saket
  • 36
  • 4
  • Yes i'll be using Promise.all but my problem is how to write and where do i need to write logic for comparing both the APIs' – Chandan Dec 11 '19 at 08:22
  • @Chandan you can add logic to the function after your promise is resolved. and update your state there and render the data. (EDITED THE SOLUTION) Also your components in the question are not properly indented , so its quite difficult to read http://mrbool.com/importance-of-code-indentation/29079 – Saket Dec 11 '19 at 09:30