sei-ec-remote / project-4-issues

Open an issue to receive help on project 4
0 stars 0 forks source link

Issue with Modal only opening last element of mapped array in React #53

Closed jfw2855 closed 2 years ago

jfw2855 commented 2 years ago

What stack are you using?

(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)

MERN

What's the problem you're trying to solve?

I'm trying to fix an issue with the modal only pulling the last item in the transactions array.

Post any code you think might be relevant (one fenced block per file)

const TransactionIndex = (props) => {
  const {coin} = useParams()
  const { user,msgAlert} = props
  const [transactions,setTransactions] = useState(null)
  const [modalOpen,setModalOpen] = useState(false)
  const [updated, setUpdated] = useState(false)
  const [selected, setSelected] = useState(null)

  let transactionsDisplay
  const location = useLocation()
  const {quantity,currPrice,daily,symbol,avgBuy,pl_amount,pl_precentage,img,name}=location.state

  console.log('name?',pl_precentage,img,name)
// USE EFFECT PSEUDOCODE
// fetch data from transaction of specific coin (backend server)
// fetch data from assets of coin (backend server) - provided by useLocation
// fetch current market data of coin (external api) - provided by useLocation

  useEffect(() => {
    viewTransactions(user,coin)
      .then((res) => {
        console.log('res.data.tranaction!',res.data.transaction)
        console.log('res.data.transactions[0]', res.data.transaction[0])
        setSelected(res.data.transaction[0])
        setTransactions(res.data.transaction) 
      })
      .catch((err) => console.log(err))
    }, [updated])

    const handleEdit = (e, transaction) => {
      setSelected(transaction)
      const handleOpen = () => {
        setModalOpen(true)
      }
      handleOpen()
    }

    if (transactions && transactions.length > 0) {
      console.log('selected', selected)
      transactionsDisplay = transactions.map(transaction => (
        <ListGroup.Item key={transaction._id}>

        <Row style={{ alignItems: 'center' }}>
          <Col>
            {transaction.type}
          </Col>
          <Col>
            {transaction.price}
          </Col>
          <Col>
            {transaction.amount}
          </Col>
          <Col>
             <BsPencilFill type='button' onClick={(e) => handleEdit(e, transaction)}/> 
             <BsTrash/>
          </Col>
        </Row>
      </ListGroup.Item>
        )) 
      }

      if (!transactions) {
        return <Spinner animation="border" role="status">
      <span className="visually-hidden">Loading</span>
    </Spinner>
  }
  return (
    <>
    <img src={img} width={50}/>
    <h5 style={{color:'white'}}>{name} ({symbol.toUpperCase()})</h5>
    <p style={{color:'white'}}>24H: {daily.toFixed(2)}%</p>
    <p style={{color:'white'}}>Balance: {(quantity*currPrice).toLocaleString('en-US', {style:'currency',currency:'USD'})}</p>
    <p style={{color:'white'}}>Quantity: {quantity} {symbol.toUpperCase()} </p>
    <p style={{color:'white'}}>Avg. Buy Price {avgBuy.toLocaleString('en-US', {style:'currency',currency:'USD'})}</p>
    <p style={{color:'white'}}>P/L: {pl_amount.toLocaleString('en-US', {style:'currency',currency:'USD'})} {pl_precentage.toFixed(2)}%</p>
    <button>Add Transaction</button>
           <ListGroup style={{ width: '85%' }}>
        <ListGroup.Item>
          <Row style={{ fontWeight: 'bold' }}>
            <Col>
              Type
            </Col>
            <Col>
              Price
            </Col>
            <Col>
              Amount
            </Col>
            <Col>
              Actions
            </Col>
          </Row>
        </ListGroup.Item>
        {transactionsDisplay}
      </ListGroup>
      <EditTransactionModal
      transaction={selected}
      show={modalOpen}
      user={user}
      msgAlert={msgAlert}
      triggerRefresh={() => setUpdated(prev => !prev)}
      updateTransaction={updateTransaction}
      handleClose={() => setModalOpen(false)}
      />  
    </>
  )
}

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

We don't see an error, but it only edits the last elements transaction data instead of updating the element selected. (clicking the edit button for the first item will render the last element's data and save the data to that last element).

What is your best guess as to the source of the problem?

It has to do with our setSelected not updating the EditTransactionModal at the handleEdit function.

What things have you already tried to solve the problem?

We tried moving this into a function, the component inside the map function and outside, but nothing seems to fix the issue. https://stackoverflow.com/questions/66532393/modal-only-shows-last-element-of-mapped-array-in-react https://stackoverflow.com/questions/57220998/react-bootstrap-modal-only-take-last-item-of-map

Paste a link to your repository here https://github.com/jfw2855/CryptoTracker-Client

timmshinbone commented 2 years ago

What happens when you just console log res.data when you get/set the transaction?

jfw2855 commented 2 years ago
Screen Shot 2022-04-27 at 3 26 45 PM
jfw2855 commented 2 years ago

transactions is just an array of the user's transaction data. We set this to transaction then map through to render coin transaction data.

Screen Shot 2022-04-27 at 3 27 48 PM
timmshinbone commented 2 years ago

You're hard-coding a specific item in the transactions array as the setSelected, and it'll always be the first item because you're using [0], find a way to get the specific transaction that has been picked