Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
Object is possibly null react/typescript

I keep running in to this error, the code works fine in plain react but in typescript it keeps throwing this error "Object is possibly null". I tried countering it using "!" but it didn't help.

second error in the log says "cannot read properties of null reading (textContent)"

I set this to false

"strictNullChecks": false,

Here is a sandbox - https://codesandbox.io/s/sweet-mclean-nrhcdq?file=/src/App.tsx

This is the fetch api call -

const [isLoading, setLoading] = useState(false);
  //storing data
  const [data, setData] = useState(false);

  //fetching data
  useEffect(() => {
    setLoading(true);

    const fetchList = async (): Promise<UsersList> => {
      const result: any = await fetch("https://randomuser.me/api/?results=20")
        .then((res) => res.json())
        .then((data) => {
          setData(data);
          setLoading(false);
          console.log(data);
          
        });
        
      return result;
    };
    fetchList();
    
    
  }, []);

This is the code that is causing me the problem, is there a better way of doing this? someone mentioned useref but im not sure how to implement it with a fetch call in useEffect.

The desired output is for any text that includes Miss to have a blue background.

const h2 = window.document.getElementById("person")!
  h2.innerHTML = h2.textContent!.replace(/[Miss]/g, "<span class='title'>Miss</span>");

.title {
background-color: blue;
}

Later in the html I have filtered and mapped through the data -

<div style={hoverStyle} className="grid grid-cols-4 gap-2 p-2 mt-20">
        {data?.results.filter((val: any)=>{
          if (searchUser === "") {
            return val
          } else if (val.name.first.toLowerCase().includes(searchUser.toLowerCase())) { 
              return val          
          } else if (val.email.toLowerCase().includes(searchUser.toLowerCase())){
            return val
          } else if 
            (val.location.city.toLowerCase().includes(searchUser.toLowerCase())){
              return val
            } 
        }).map((d: any) => (
              
          <div style={hoverStyle} className=" ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300  border-white shadow-slate-500 bg-white hover:opacity-95 rounded-lg container p-5">
            <img className="rounded-full w-44 h-44 " src={d.picture.large} />
            <h2 id="person" >{d.name.title}</h2>

Any ideas?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are mapping through an array so it creates multiple h2 elements that is why need to select all h2 elements, also do that when data loading finished. try these changed lines.

 let h2 = document.querySelectorAll("h2")
  h2.innerHTML = !isLoading && h2.textContent?.replace(/[Miss]/g, "<span class='title'>Miss</span>");

Also here is the screen shot taken from your sandbox attached after doing that. Hope you are looking for the same.enter image description here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda