r/reactjs • • Sep 01 '21

Needs Help Beginner's Thread / Easy Questions (September 2021)

Previous Beginner's Threads can be found in the wiki.

Ask about React or anything else in its ecosystem :)

Stuck making progress on your app, need a feedback?
Still Ask away! We’re a friendly bunch πŸ™‚


Help us to help you better

  1. Improve your chances of reply by

    1. adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
    2. describing what you want it to do (ask yourself if it's an XY problem)
    3. things you've tried. (Don't just post big blocks of code!)
  2. Format code for legibility.
  3. Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.

New to React?

Check out the sub's sidebar! πŸ‘‰
For rules and free resources~

Comment here for any ideas/suggestions to improve this thread

Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!


12 Upvotes

177 comments sorted by

View all comments

Show parent comment

1

u/badboyzpwns Sep 11 '21 edited Sep 11 '21

A quick follow up Nathan! so I decided to use your first solution. I made a new renderMe() and encountering a similar problem:

Sandbox:

https://codesandbox.io/s/quiet-flower-nz2kl?file=/src/App.tsx:0-839

Here's my new code now:

    import "./styles.css";
import React, { useState, useEffect } from "react";
interface A {
  type: "A";
  aHi: string;
}
interface B {
  type: "B";
  bHi: string;
}

export default function App() {
  const [hoverData, setHoverData] = useState<null | A | B>(null);
  const A = "A";
  const B = "b";
  //New Implementation:
  const renderMe = (type: "A" | "B") => {
    //Can we also refer to A and B through a variable?

    setHoverData({ type: type, aHi: "hi" }); //WARNING:Typescript says Type '"A" | "B"' is not assignable to type '"A"'.
    //Type '"B"' is not assignable to type 'A'
  };

  useEffect(() => {
    renderMe("A");
  }, []);
  return (
    <div className="App">
      <h1
        onClick={() => {
          console.log(hoverData && hoverData.bHi);
        }}
      >
        Hello CodeSandbox
      </h1>
    </div>
  );
}

1

u/Nathanfenner Sep 11 '21

Here, TypeScript is just catching a bug - renderMe asks for a type which is either "A" or "B".

If it's a "B", then { type: type, aHi: "hi" } isn't an A, since it's { type: "B", aHi: "hi" } - its type and its field don't match.

This will work if you fix the type of renderMe: it only works when it's given an "A", so it should have type: "A" only as its argument.

Alternatively, it should look at type and do something different if it's "B", e.g.

if (type === "A") {
  setHoverData({ type: type, aHi: "hi" }); 
} else {
  setHoverData({ type: type, bHi: "bye" }); 
}

1

u/badboyzpwns Sep 12 '21

Thank you again! appreciate your help!