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

199
Visualizações
How to get access to the PromiseResult in React when calling Azure Cosmos DB api

I'm trying to pull some rows from a Cosmos DB and then map through them to display a component for each. All of the documentation I can find for the Azure Cosmos DB API logs rows to the console one by one but I can't find one then tells you how to return the whole string.

I'm new to this so am probably doing it horribly wrong but I am now stuck and cannot move on. Hope you can help ...

In my App.js I have this

function App() {
const [newMembers, setNewMembers] = useState(dataFetch());

In my dataFetch.js I have

export default async function dataFetch() {
  const { endpoint, key, databaseId, containerId } = config;
  const client = new CosmosClient({ endpoint, key });
  const database = client.database(databaseId);
  const container = database.container(containerId);

  // Make sure Tasks database is already setup. If not, create it.
  // await dbContext.create(client, databaseId, containerId);

  try {
    console.log(`Querying container: Items`);

    // query to return all items
    const querySpec = {
      query: "SELECT * from c",
    };

    // read all items in the Items container
    const { resources: items } = await container.items
      .query(querySpec)
      .fetchAll();
    return items;
  } catch (err) {
    console.log(err.message);
  }
}

When I console.log the result back it says

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(3)
0: {id: '154', forename: 'Fred', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
1: {id: '416', forename: 'Lee', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
2: {id: '900', forename: 'Kathryn', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
length: 3
[[Prototype]]: Array(0)

I saw something elsewhere about using .then but when I tried

const { resources: items } = await container.items
  .query(querySpec)
  .fetchAll()
  .then(() => {
    return items;
  });

It said "dataFetch.js:33 Cannot access 'items' before initialization"

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

0

What you're doing in the first two code blocks is perfectly fine. However with putting the result of dataFetch() into the newMembers state, you're just storing the promise in there which just get's resolved at some point and you can retrieve the results at any point with newMembers.then(actualResult => ...).

However, I think you would rather like to keep the actual members array in the newMembers state. This can be done by e.g.:

function App() {
    const [newMembers, setNewMembers] = useState([]); // initially set to an empty array

    useEffect(() => {
        dataFetch().then(members => setMembers(members));
    }, []); // providing an empty array means: run this effect only once when this component is created.

    // do something with the newMembers. Initially, it will be [] 
    // but as soon as the data is retrieved from the DB, the actual data will be 
    // in the state and the component will be rerendered.
}
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