1

I am trying to make an app on forex trade that renders updated value..When the value changes i want to display colour that shows the value has been changed..if the previous value is less than the updated value it should show red,green for greater and blue for same.I am using useref() to store value and using it in use effect() to get the previous value.I do get the previous value in console but when i display it,it shows updated value..image of the output is attached1

function App() {
  const [state, dispatch] = useReducer(reducer, initalState);
  const { websocketIsAlive, setData } = state;
  const temp = useRef();
  const ws = useRef(null);
  const refer = useRef();
  

  const URL = "ws://localhost:3030";
const renderData = (el) => {
    function onValueChange(el, refs, el1) {
      try {
        if (refs !== undefined) {
          if (el.stock_symbol === refs.stock_symbol) {
            console.log("on function:", el);
            console.log(`el: ${el[el1]} refs:${refs[el1]}`);

            if (el[el1] === refs[el1]) {
              console.log(
                `${el.stock_symbol}:${el1}->${el[el1]} is equal to${refs.stock_symbol}:${refs[el1]}`
              );
              return "blue";
            }
            if (el[el1] > refs[el1]) {
              console.log(
                `${el.stock_symbol}:${el1}-> ${el[el1]} is greater to${refs.stock_symbol}:${refs[el1]}`
              );
              return "green";
            }
            if (el[el1] < refs[el1]) {
              console.log(
                `${el.stock_symbol}:${el1}-> ${el[el1]} is less to${refs.stock_symbol}:${refs[el1]}`
              );
              return "red";
            }
          } else {
            // console.log(
            //   `${el.stock_symbol} not matches ${refer.current.stock_symbol}`
            // );
            // console.log(value);

            return "white";
          }
        }
      } catch (error) {}
    }

    const changeprice = (el, el1) => {
      try {
        if (el[el1] > 0) {
          return "green";
        }
        if (el[el1] === 0) {
          return "black";
        } else if (el[el1] < 0) {
          return "red";
        }
      } catch (error) {}
    };

    // "#F5C6A5"
    // #C6D57E
    try {
      return (
        <>
          <tr>
            <td style={{ color: "blue" }}>{el.stock_symbol}</td>
            <td
              style={{
                backgroundColor: onValueChange(
                  el,
                  refer.current,
                  "stock_current_price"
                ),
              }}
            >
              {el.stock_current_price} {refer.current.stock_current_price}
            </td>
            <td
            // style={{
            //   backgroundColor: changeBgColor(el, "stock_bid_volume"),
            // }}
            >
              {el.stock_bid_volume}
            </td>
            <td
            // style={{
            //   backgroundColor: onValueChange(
            //     el,
            //     refer.current,
            //     "stock_bid_price"
            //   ),
            // }}
            >
              {el.stock_bid_price}
            </td>
            <td>{el.stock_ask_price}</td>
            <td>{el.stock_ask_volume}</td>
            <td
              style={{
                // backgroundColor: changeColorOnInt(el, "stock_change"),
                color: changeprice(el, "stock_change"),
              }}
            >
              {el.stock_change}
            </td>
            <td
              style={{
                // backgroundColor: changeColorOnInt(el, "stock_change"),
                color: changeprice(el, "stock_change_p"),
              }}
            >
              {el.stock_change_p}
            </td>
            <td>{el.stock_open}</td>
            <td>{el.stock_high}</td>
            <td>{el.stock_low}</td>
            <td>{el.stock_volume}</td>
          </tr>
        </>
      );
    } catch (error) {
      console.log(error);
    }
  };
const connect = () => {
    ws.current = new WebSocket(URL);

    ws.current.onopen = () => {
      console.log("Connected websocket");
      dispatch({ type: Actions.WEBSOCKET_IS_ALIVE, payload: true });
    };
    ws.current.onmessage = (evt) => {
      const data = JSON.parse(evt.data);
      // console.log("empty effect ", refer.current);
      // console.log("data at empty use effect");
      // console.log("data", data.data);
      const evtData = data.data;
      console.log("evtData", evtData);
      dispatch({ type: Actions.UpdateData, payload: { evtData, refer, temp } });
    };
    ws.current.onclose = (e) => {
      console.log("Socket is closed", e.reason);
    };
  };
  const fetchApi = async () => {
    try {
      const result = await fetch(
        {API-KEY},
        {
          // mode: "no-cors",
          method: "POST",
          headers: {
            // 'Content-Type': 'application/json'

            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      const res = await result.json();
      //   console.log("res", res);
      dispatch({ type: Actions.SET_DATA, payload: res });
      console.log("after dispatch");
      connect();
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchApi();
  }, []);

 return (
    <div>
      <table className="table table-bordered">
        <thead>
          <tr>
            <th scope="col">Symbol</th>
            <th scope="col">Last Price</th>
            <th scope="col">Bid Size</th>
            <th scope="col">Bid</th>
            <th scope="col">Offer</th>
            <th scope="col">Offer Size</th>
            <th scope="col">Stock Change</th>
            <th scope="col">Stock Change %</th>
            <th scope="col">Open</th>
            <th scope="col">High</th>
            <th scope="col">Low</th>
            <th scope="col">Volume</th>
          </tr>
        </thead>
        <tbody>
          {setData === null ? (
            <Table />
          ) : (
            Object.entries(setData).map((item, index) => {
              {
                /* console.log("item", item); */
              }

              return renderData(item[1]);
            })
          )}
        </tbody>
      </table>
    </div>
  );
}
function reducer(state, action) {
  switch (action.type) {
    case Actions.UpdateData:
      let incomingData = action.payload.evtData;
 
      let newData = { ...state.setData };
      try {
        if (state.setData !== null) {
          Object.entries(state.setData).map((el) => {
           

            if (el[1].stock_symbol === incomingData.s) {
           
              action.payload.temp.current = { ...el[1] };
              console.log(" temp", action.payload.temp.current);
              action.payload.refer.current = action.payload.temp.current;

   

              el[1].stock_change_p = incomingData.pch;

              // .toFixed(2);
              el[1].ask_price = incomingData.ap;
              el[1].ask_volume = incomingData.av;
              el[1].bid_price = incomingData.bp;
              el[1].bid_volume = incomingData.bv;
              el[1].stock_change = incomingData.ch;
              el[1].stock_change_p = incomingData.pch.toFixed(2);
              el[1].stock_current_price = incomingData.c;
              el[1].stock_high = incomingData.h;
              el[1].stock_low = incomingData.l;
              el[1].stock_open = incomingData.o;
              el[1].stock_volume = incomingData.v;

              // console.log(el);
            }
          });
          // console.log("incomingdata", incomingData.s);
          return { ...state, setData: newData };
        }
      } catch (error) {
        console.log(error);
      }}

I am using react use reducer to build..and passing data through web-socket.

unknown
  • 11
  • 2
  • Could you provide [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)? – Andrey Dec 03 '21 at 06:36

0 Answers0