saint
saint

Reputation: 13

I'm trying to render two different strings from 2 different API calls in the same component

import { useState, useEffect } from 'react';
import socketConnection from '../../connection';
import NavBar from '../../../Component/NavBar.';

const ws = socketConnection();

export default function GetEvent() {
  const [matchTime, setMatchTime] = useState('');
  const [teamNames, setTeamNames] = useState('');
  const [market, setMarket] = useState('');
  const [isLoading, setLoading] = useState(true);
  const [socketData, setSocketData] = useState([]); // array of objects.



useEffect(() => {
    ws.onopen = () => ws.send(
      /* eslint-disable */
        JSON.stringify({
          keys: ['xyz'],
          type: 'getEvent',
          id: 111,
          keys: ['skd'],
          type: 'getMarket',
          id: 222,
        }),
      );
function handleMessage(event) {
  console.log('Handling message');
  setLoading(true);
  const parsedData = JSON.parse(event.data);
  console.log(parsedData);
  setMatchTime(parsedData.data.startTime);
  setTeamNames(parsedData.data.name);
  setSocketData((currentSocketData) => [...currentSocketData, parsedData]);
  setMarket((currentSocketData) => [...currentSocketData, parsedData[1]]);
  setLoading(false);
}
    ws.addEventListener('message', handleMessage);

    return () => ws.removeEventListener('message', handleMessage);
  }, []);

@developers console

console.log(matchTime); array of undefined objects. -expected '2020 09 02' console.log(teamNames); HalfTime/FullTime -expected 'rangers vs wolves' console.log(market); array of undefined objects. -expected 'HalfTime/FullTime'

I have also tried rendering as different components, but that doesn't make sense, as they are just strings from the API.

return (
    <>
      <NavBar />
      <div className="footyevent" data-testid="footy-event-id">
        <div className="container">
          <h1>Football</h1>
          <div className="title-box">
            {isLoading && <div className="loading">Not Connected... Please 
             Refresh</div>}
          </div>
          <div className="title-box">
            <div className="startTime" data-testid="event-time-id">
              Date & Time: {matchTime}  {/* blanc */}
            </div>
          </div>
          <div className="title-box">
            <div className="teams" data-testid="playing-teams-id">
              {teamNames}  {/* HalfTime/FullTime */}
            </div>
          </div>
          <div className="title-box">
            <div className="socket-data" data-testid="socket-data-id">
              {socketData.map((x, index) => (
                <p>
                  {x.data.name}  {/* HalfTime/FullTime */}
                </p>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

Behaviour is fine with a single API call of

JSON.stringify({
          keys: ['xyz'],
          type: 'getEvent',
          id: 212,
        }),
      );

update: I'm finding it difficult now to resolve or map over the data(objects) received from the WebSocket server response.

export default function GetEvent() {
  const [isLoading, setLoading] = useState(true);
  const [socketData, setSocketData] = useState([]); // objects.

  useEffect(() => {
    ws.onopen = () => {
      ws.send(
        /* eslint-disable */
        JSON.stringify({
          keys: ['xyz'],
          type: 'getEvent',
          id: 111,
        }),
      );
      ws.send(
        /* eslint-disable */
        JSON.stringify({
          keys: ['skd'],
          type: 'getMarket',
          id: 222
        }),
      );
    };


    function handleMessage(event) {
      console.log('Handling message');
      setLoading(true);
      const parsedData = JSON.parse(event.data);
      console.log(parsedData);
      setSocketData((currentSocketData) => [...currentSocketData, parsedData]);
      setLoading(false);
    }

    ws.addEventListener('message', handleMessage);

    return () => ws.removeEventListener('message', handleMessage);
  }, []);



socketData.forEach(x => x.forEach(y => {
    if (x.type === 'EVENT_DATA') {
      console.log(`event data: ${y.data.name}`);
    } else if (x.type === 'BET_DATA') {
      console.log(y.data.name);
    }
  }));
  

return (
    <>
      <div className="title-box">
    <div key="uniqueId2" className="teams" data-testid="playing-teams-id">
      {socketData.map(data1 => console.log(data1))}
    </div>
</div>
    </>
  );
}

Console data & errors

iterating over socket data logged:

Uncaught TypeError: x.forEach is not a function

console.log(data1):

{type: 'EVENT_DATA', data: {…}}
data: {
  id: 1;
  name: 'A';
  date: '12020507'
}
{type: 'MARKET_DATA', data: {…}}
data: {
  id: 1;
  name: 'Final Result';
}

console.log(data1[0])

undefined

console.log(data1.name):

'A'
'Final Result'

Upvotes: 0

Views: 74

Answers (2)

saint
saint

Reputation: 13

This is my answer, kindly refactor

export default function GetEvent() {
  const [socketData, setSocketData] = useState([]);

  useEffect(() => {
    ws.onopen = () => {
      ws.send(
      );
      ws.send(
      );
    };


    function handleMessage(event) {
      
    }

    ws.addEventListener('message', handleMessage);

    return () => ws.removeEventListener('message', handleMessage);
  }, []);





const myDom1 = socketData.map((dataObject, index, arr) => {
    if (dataObject.type === 'event-data') {
      return dataObject.data.startTime
    } 
  })
  const myDom2 = socketData.map((dataObject, index, arr) => {
    if (dataObject.type === 'market') {
      return dataObject.data.name
    } 
  })
  const myDom3 = socketData.map((dataObject, index, arr) => {
    same...

    } 
  })



return (
    <>
     <div className="t-b">
            <div key="uniqueId1" className="teams" data-testid="">
              <p>{myDom1}</p>
            </div>
          </div>
          <div className="t-b">
            <div key="uniqueId2" className="teams" data-testid="">
              <p>{myDom2}</p>
            </div>
          </div>
          <div className="t-b">
            <div key="uniqueId3" className="" data-testid="">
              <p>{myDom3}</p>
            </div>
          </div>
    </>
  );
}

Upvotes: 0

3limin4t0r
3limin4t0r

Reputation: 21150

Your main issue is probably:

JSON.stringify({
  keys: ['xyz'],
  type: 'getEvent',
  id: 111,
  keys: ['skd'],
  type: 'getMarket',
  id: 222,
})

If you use duplicate keys in object literals they will override the previous value.

({ a: 1, b: 2, c: 3, a: 4, b: 5 }) //=> { a: 4, b: 5, c: 3 }

This means that the value of the first 3 keys (keys, type and id) will be lost.

I don't know what your socket is expecting. If it accepts arrays you should use the following instead.

ws.send(JSON.stringify([{
  keys: ['xyz'],
  type: 'getEvent',
  id: 111,
}, {
  keys: ['skd'],
  type: 'getMarket',
  id: 222,
}]))

Alternatively you could send 2 separate requests.

ws.send(JSON.stringify({
  keys: ['xyz'],
  type: 'getEvent',
  id: 111,
}))
ws.send(JSON.stringify({
  keys: ['skd'],
  type: 'getMarket',
  id: 222,
}))

For this last one you might have to adjust the handleMessage function. Because instead of both results being in a single response the handler will be called 2 times.

Upvotes: 0

Related Questions